Reputation: 4047
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
Upvotes: 0
Views: 3880
Reputation: 4822
The best way to do this would be to only have one file. It will save you wasting memory and worrying about how to change a file name. If you open file with the write command the files contents will be emptied.
I've wrote this quickly now I cant guarantee that it works but its along the right lines.
import csv
def OpenFile(fname):
with open(fname,'r') as f:
reader = csv.reader(f)
file = []
for row in reader:
file.append(row)
return file
def WriteFile(fname,data):
with open(fname,'w') as f:
writer = csv.writer(f)
for row in data:
writer.writerow(row)
rnum = randint(100)
file = OpenFile('file.csv')
file[rnum][2] = 'TRUE'
WriteFile(fname,file)
Upvotes: 0
Reputation: 134571
You're almost there. Notice what you're doing in the loop and what you're writing. you have this:
for i, row in enumerate(reader):
if i == rnum:
row[2] = 'TRUE'
writer.writerow(row)
I believe what you want to do is enumerate over the rows of the file and copying them over to the file you're writing to. You don't actually write anything except the last row enumerated over since your writes are not within the loop, it's outside. Make sure it's part of the loop.
for i, row in enumerate(reader):
if i == rnum:
row[2] = 'TRUE'
writer.writerow(row)
On a side note, it would be better to open your files using the with
statement. It will help manage the files for you so you don't have to close it at the end, it will be taken care of for you.
rnum = randint(1,100)
with open('file.csv', 'rb') as file1, open('file11.csv', 'wb') as file2:
reader = csv.reader(file1)
writer = csv.writer(file2)
for i, row in enumerate(reader):
if i == rnum:
row[2] = 'TRUE'
writer.writerow(row)
Upvotes: 1