1

I'm attempting to rewrite specific cells in a csv file using Python.

However, whenever I try to modify an aspect of the csv file, the csv file ends up being emptied (the file contents becomes blank).

Minimal code example:

import csv
ReadFile = open("./Resources/File.csv", "rt", encoding = "utf-8-sig")
Reader = csv.reader(ReadFile)
WriteFile = open("./Resources/File.csv", "wt", encoding = "utf-8-sig")
Writer = csv.writer(WriteFile)
for row in Reader:
    row[3] = 4
    Writer.writerow(row)
ReadFile.close()
WriteFile.close()

'File.csv' looks like this:

1,2,3,FOUR,5
1,2,3,FOUR,5
1,2,3,FOUR,5
1,2,3,FOUR,5
1,2,3,FOUR,5

In this example, I'm attempting to change 'FOUR' to '4'.

Upon running this code, the csv file becomes empty instead.

So far, the only other question related to this that I've managed to find is this one, which does not seem to be dealing with rewriting specific cells in a csv file but instead deals with writing new rows to a csv file.

I'd be very grateful for any help anyone reading this could provide.

5
  • 1
    Open the file with a+ instead. Commented Dec 2, 2016 at 15:41
  • @j-darbyshire I've replaced "rt" and "wt" with "a+" and it's still wiping the file. Am I doing it wrong? Commented Dec 3, 2016 at 0:17
  • 1
    Set the reader the start of the file. Directly below the line ReadFile = open... add the line ReadFile.seek(0). Now your code should run as expected. Commented Dec 3, 2016 at 2:01
  • @j-darbyshire Now the program seems to be keeping the original content and adding the modified content after it. Should I still be using two separate 'open' variables (ReadFile & WriteFile) both using 'a+'? Commented Dec 3, 2016 at 23:38
  • 1
    I misunderstood your aim. See answer for correct solution. Commented Dec 4, 2016 at 1:14

2 Answers 2

2

The following should work:

import csv

with open("./Resources/File.csv", "rt", encoding = "utf-8-sig") as ReadFile:
    lines = list(csv.reader(ReadFile))

with open("./Resources/File.csv", "wt", encoding = "utf-8-sig") as WriteFile:
    Writer = csv.writer(WriteFile)
    for line in lines:
        line[3] = 4
        Writer.writerow(line)
Sign up to request clarification or add additional context in comments.

Comments

2

When you open a writer with w option, it will delete the contents and start writing the file anew. The file is therefore, at the point when you start to read, empty.

Try writing to another file (like FileTemp.csv) and at the end of the program renaming FileTemp.csv to File.csv.

1 Comment

Thank you, this seems like the most logical thing to do in this situation. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.