PredAtor
PredAtor

Reputation: 7

Delete row or cell in a csv file

I want to delete rows from a csv file as they are processed. My file:

 Sr,Name1,Name2,Name3
 1,Zname1,Zname2,Zname3
 2,Yname1,Yname2,Yname3
 3,Xname1,Xname2,Xname3

I want to read row by row and delete the row which has been processed. So the file will be now:

2,Yname1,Yname2,Yname3
3,Xname1,Xname2,Xname3

The solutions which are provided on other questions are:

  1. read the file
  2. use next() or any other way to skip the row and write the remaining rows in an updated file

I want to delete the row from the original file which was entered in .reader() method

My code:

 with open("file.txt", "r") as file
 reader = csv.reader(file)
 for row in reader:
     #process the row
     #delete the row

I have not been able to figure out how to delete/remove the row.

I want the change to be in the original file.txt because I will be running the program many times and so each time it runs, file.txt will already be present and the program will start from where it ended the last time.

Upvotes: 1

Views: 8189

Answers (3)

Malik Hamza
Malik Hamza

Reputation: 350

Just read the csv file in memory as a list, then edit that list, and then write it back to the csv file.

lines = list()
members= input("Please enter a member's name to be deleted.")
with open('mycsv.csv', 'r') as readFile:
    reader = csv.reader(readFile)
    for row in reader:
        lines.append(row)
        for field in row:
            if field == members:
                lines.remove(row)
with open('mycsv.csv', 'w') as writeFile:
    writer = csv.writer(writeFile)
    writer.writerows(lines)

You can delete column like this:

We can use the panda pop () method to remove columns from CSV by naming the column as an argument.

  • Import Pandas.
  • Read CSV File.
  • Use pop() function for removing or deleting rows or columns from the CSV files.
  • Print Data.

Upvotes: 2

PredAtor
PredAtor

Reputation: 7

Since the pandas package deals with big data, there is no solution in basic Python. You will have to import pandas.

import pandas
df=pandas.read_csv("file_name.txt")
df.set_value(0,"Name3",new_value)
df.to_csv("file_name.txt", index=False) 

This code edits the cell in the 0th row and Name3 column. The 0th row is the first row below the header. Thus, Zname3 will be changed to something else. You can similarly delete a row or a cell.

I have not tried this code but it is supposed to work in the required manner.

Upvotes: 0

Joep
Joep

Reputation: 832

You probably can find inspiration here: How to delete a specific line in a file?.

And don't forget to grant write permission when opening the file.

Upvotes: 0

Related Questions