0

我想仅在每行的第三帧中重写 csv 文件中的值。前两帧将是相同的。

但是在这段代码的输出中是

builtins.TypeError:'_csv.writer' 对象不可迭代

import csv

with open('friends.csv', mode='w') as file: 
    writer = csv.writer(file, delimiter=';', quotechar='"', quoting=csv.QUOTE_MINIMAL)
   
new_age = "25"

for line in writer:
    writer.writerow(['line[0]','line[1]',new_age]) #it means that first two frmaes will be rewrited for same value like they are, last one will be rewrited to new_age.

你知道如何让它变得更好吗?

谢谢

4

3 回答 3

1

csv 文件是一个文本文件。这意味着更改它的幸运方法是编写一个不同的文件并在最后用原始名称重命名新文件:

# open the files
with open('friends.csv', mode='r') as oldfile, open(
        'friends.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)
    # copy everything changing the third field
    for row in reader:
        writer.writerow([row[0], row[1], ,new_age])
# ok, time to rename the file
os.replace('friends.tmp', 'friends.csv')
于 2021-10-27T14:29:47.370 回答
0

看看convtools库,它提供了一个 csv 助手和许多数据处理原语。

from convtools import conversion as c
from convtools.contrib.tables import Table

# if there's header and "age" is the column name
Table.from_csv("friends.csv", header=True).update(
    age=25
    # to reduce current ages you could:
    # age=c.col("age").as_type(int) - 10
).into_csv("processed_friends.csv")

# if there's no header and a column to rewrite is the 2nd one
Table.from_csv("friends.csv").update(COLUMN_1=25).into_csv(
    "friends_processed.csv", include_header=False
)

# if replacing the current file is absolutely needed
rows = list(
    Table.from_csv("friends.csv", header=True)
    .update(age=25)
    .into_iter_rows(list, include_header=True)
)
Table.from_rows(rows).into_csv("friends.csv", include_header=False)

于 2021-10-27T15:03:51.750 回答
0

我认为你需要定义你的 CSV 文件CSV_File = 'friends.csv

然后打电话with open(CSV_file,'wb') as file: ,你需要删除你周围的引号line[1] line[0]

跳过前两行使用模式wb而不是打开 outfilew

于 2021-10-27T14:06:28.767 回答