In pseudocode: I need a block of code that can access a .csv file, go to the n
th row, with n
being a predetermined random number between 1, 100, go to the 3rd column of nth row, and replace the 'FALSE'
string there with a string that reads 'TRUE'
.
Here's what SO has told me so far: I might need to read the file, write over it to a new file, and then rename back to the original file name(?) for this to work.
Here's the code I have thus far:
rnum = randint(1,100)
file1 = open('file.csv', 'rb')
reader = csv.reader(file1)
file2 = open('file11.csv', 'wb')
writer = csv.writer(file2)
for i, row in enumerate(reader):
if i == rnum:
row[2] = 'TRUE'
writer.writerow(row)
file1.close()
file2.close()
The code doesn't work -- in the file1.csv
file, all that is printed is the last row of the original .csv file, which isn't what I want.
I suppose ideally the whole file.csv
file should be transferred to the file1.csv
, but with the n
th row modified as described above. Thoughts?
Sorry if this is an obvious question, I just started programming.
Related SO questions on this topic:
Change specific value in CSV file via Python
Writing to a particular cell using csv module in python - this question suggests creating a function for this issue?
read and write on same csv file