[英]How to rewrite only one frame (line[2]) in line in .csv file?
I would like to rewrite value in csv file only in third frame for every line.我想仅在每一行的第三帧中重写 csv 文件中的值。 First two frames would be same.
前两帧是相同的。
But in output of this code is但是在这段代码的输出中
builtins.TypeError: '_csv.writer' object is not iterable 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.
Do you know how makes it better?你知道如何让它变得更好吗?
Thank you谢谢
A csv file is a text file. csv 文件是一个文本文件。 That means that the blessed way to change it is to write a different file and rename the new file with the original name in the end:
这意味着更改它的好方法是编写一个不同的文件并在最后使用原始名称重命名新文件:
# 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')
I think you need to Define your CSV file CSV_File = 'friends.csv
我认为你需要定义你的 CSV 文件
CSV_File = 'friends.csv
then call with open(CSV_file,'wb') as file:
and you need to remove the quotes surrounding your line[1]
line[0]
然后
with open(CSV_file,'wb') as file:
调用with open(CSV_file,'wb') as file:
您需要删除line[1]
line[0]
周围的引号
to skip first two lines open outfile with mode wb
instead of w
跳过前两行,用
wb
模式打开 outfile 而不是w
Have a look at convtools library, which provides both a csv helper and a lot of data processing primitives.看看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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.