-1

我在这里有一个三行三列的 csv 文件。

这是csv文件

起初我想打印所有的行。随后,对于它们中的每一个,程序检查它是否写在第二个字段(索引 1)USA 中。如果是这样,程序将从第三个字段中获取价格并将其乘以 2。

现在我需要重写这个翻倍的价格而不是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)

有人已经建议我使用创建一个新文件。但是当我想首先处理文件中的数据时,这会导致问题。

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')

谢谢你的答案

4

1 回答 1

0

new_price您在循环的每次迭代中都在改变for。因此,您应该在更改值的循环中写入行:

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')
于 2021-10-27T16:35:57.613 回答