I have a CSV file that looks as such:
header1, header2, header3, header4
1, 2, 3, abc
4, 5, 6, abc
7, 8, 9, abc
My goal is to only change the values marked as "abc". I want the file to look like this when I'm done:
header1, header2, header3, header4
1, 2, 3, test
4, 5, 6, test
7, 8, 9, test
The code I have come up with so far is as follows:
import csv
with open('test2-2.csv', 'w') as csvout:
write=csv.writer(csvout, delimiter=',', lineterminator='\r')
with open('test2.csv', 'rb') as csvfile:
read=csv.reader(csvfile, delimiter=',')
for row in read:
row[3]="test"
write.writenow(row)
The problem with this code is that it overwrites the "header4" location as well, so it comes out looking like this:
header1, header2, header3, test
1, 2, 3, test
4, 5, 6, test
7, 8, 9, test
Is there any way to specify the index locations I want to change?
Thanks for any help!
Here is the new code that works with this example:
import csv
with open('test2-2.csv', 'w') as csvout:
write=csv.writer(csvout, delimiter=',', lineterminator='\r')
with open('test.csv', 'rb') as csvfile:
read=csv.reader(csvfile, delimiter=',')
header=next(read)
write.writerow(header)
for row in read:
row[3]="test"
write.writerow(row)
If you're just looking for a way to treat the header row separately, that's pretty easy: Just process the first row separately.
with open('test2-2.csv', 'w') as csvout:
write=csv.writer(csvout, delimiter=',', lineterminator='\r')
with open('test2.csv', 'rb') as csvfile:
read=csv.reader(csvfile, delimiter=',')
header = next(read)
write.writerow(header)
for row in read:
row[3]="test"
write.writenow(row)
(Note that this still has the same bugs are your original code—at least one typo, writenow
, a missing skipinitialspace=True
, etc.)
If you want to change things by some different rule, just write a different transformation. As long as you can describe it in English, you should be able to convert it to Python pretty easily.
For example, if you wanted to change any 6
in any column into test
:
for row in read:
row = ('test' if col == '6' else col for col in row)
write.writenow(row)
Or, if you wanted to change column 2 of row 3 into test
:
for i, row in enumerate(read):
if i == 3:
row[2] = 'test'
write.writenow(row)
Or, if you wanted to change any 6
in column 2 of any row:
for i, row in enumerate(read):
if row[2] == '6':
row[2] = 'test'
write.writenow(row)
… and so on.
Just wrap your replacing code with an if
block, and use enumerate()
(see #added comments):
import csv
with open('test2-2.csv', 'w') as csvout:
write=csv.writer(csvout, delimiter=',', lineterminator='\r')
with open('test2.csv', 'rb') as csvfile:
read=csv.reader(csvfile, delimiter=',')
for row in enumerate(read): #modified
if row[0] >= 1: #added
row[1][3]="test"
write.writenow(row)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.