[英]How to rewrite only one field (line[n]) in csv but in same time be able to work with data?
I have a csv file with three lines and three columns here.我这里有一个包含三行三列的 csv 文件。
At first I want to print all the lines.起初我想打印所有的行。 Subsequently, for each of them, program check whether it is written in the second field(index 1) USA.
随后,对于它们中的每一个,程序检查它是否被写入第二个字段(索引 1)美国。 If so, program will take the price from the third field and multiply it by two.
如果是这样,程序将从第三个字段中获取价格并将其乘以 2。
Now I need to rewrite this doubled price instead of 2000 (in line with the USA)现在我需要重写这个翻倍的价格而不是 2000(与美国一致)
import csv
with open('countries.csv', 'r') as source:
reader = csv.reader(source)
writer = csv.writer(source)
for line in reader:
print(*line, sep=';')
with open('countries.csv', 'r') as source:
reader = csv.reader(source)
for line in reader:
if line[2] == "USA":
actual_price = int(line[2])
print(actual_price)
new_price = int(actual_price) * 2
print(new_price)
Someone has already advised me to use the creation of a new file.有人已经建议我使用创建一个新文件。 But this causes problems when I want to work with the data in the file first.
但是当我想首先处理文件中的数据时,这会导致问题。
import csv
import os
with open('countries.csv', mode='r') as oldfile, open(
'countries.tmp', mode='w', newline='') as newfile:
# define a reader and a writer
reader = csv.reader(oldfile, delimiter=';', quotechar='"')
writer = csv.writer(newfile, delimiter=';', quotechar='"',
quoting=csv.QUOTE_MINIMAL)
for line in reader:
print(*line, sep=';')
# copy everything changing the third field
for line in reader:
if line[2] == "USA":
actual_price = int(line[2])
print(actual_price)
new_price = int(actual_price) * 2
print(new_price)
for row in reader:
writer.writerow([row[0], row[1], ,new_price])
# ok, time to rename the file
os.replace('countries.tmp', 'countries.csv')
Thank you for answer谢谢你的答案
You are changing new_price
at every iteration of your for
loop.您在
for
循环的每次迭代中都在更改new_price
。 You should therefore be writing the row within the loop where you change the value:因此,您应该在更改值的循环中写入行:
with open('countries.csv', mode='r') as oldfile, open('countries.tmp', mode='w', newline='') as newfile:
reader = csv.reader(oldfile, delimiter=';', quotechar='"')
writer = csv.writer(newfile, delimiter=';', quotechar='"', quoting=csv.QUOTE_MINIMAL)
for row in reader:
price = int(row[2])
if row[1] == "USA":
price = price*2
writer.writerow([row[0], row[1], price])
os.replace('countries.tmp', 'countries.csv')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.