Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

editing a csv file

Status
Not open for further replies.

shussai2

Programmer
Aug 28, 2003
42
CA
Hi,

I am using a csv module to read a spreadsheet. Now what I want to do is change one of the rows in the spreadsheet. I do not want the same row repeated again when I csv.writer to write a row. I simply want to read a row from csv file, change a value in that row and write it back into the spreadsheet without repeating it in the spreadsheet. Partial code is below. Initially the csv file contains a row which is read as ['A', '1'] and I want to change it to ['A', '3']. But of course I want to get rid of the row ['A', '1'] initially there.


self._file = open("test.csv", "r+")
self._filereader = csv.reader(self._file)
self._filewriter = csv.writer(self._file)

for row in self._filereader:
if row[0] == 'A':
self._newrow = ['A', '3']
self._filewriter.writerow(self._newrow)
self._file.close()
 
If you're using the csv module then you're under a basic misunderstanding. Actually, even if you aren't, you're operating under the same basic misunderstanding.

The misunderstanding is that you can edit the contents of the file like you're doing. Your approach would lend itself to reading the old file and writing a new file.

To edit the file in place you would have to read until you find the specific location of the data you want to overwrite, seek to that position, write the new data, then close the file. "r+" will not allow you to do that.

Personally, I think it's easier to write a new file, then rename the old and new. And safer.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top