0

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

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

There 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.....

PredAtor
  • 11
  • 2
  • 5
  • A CSV file is probably less ideal if you typically want to remove stuff from the beginning. Importing the data to e.g. SQLite and deleting rows from the resulting database will be both faster and more robust. – tripleee May 07 '21 at 09:29
  • @Prophet--I don't see how this is a duplicate of your linked question since this post is about **how to delete rows as they are processed**. A relevant duplicate would be [Python delete row in file after reading it](https://stackoverflow.com/questions/53372874/python-delete-row-in-file-after-reading-it). – DarrylG May 07 '21 at 09:34

0 Answers0