[英]How to rewrite only one frame (line[2]) in line in .csv file?
我想僅在每一行的第三幀中重寫 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.
你知道如何讓它變得更好嗎?
謝謝
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')
我認為你需要定義你的 CSV 文件CSV_File = 'friends.csv
然后with open(CSV_file,'wb') as file:
調用with open(CSV_file,'wb') as file:
您需要刪除line[1]
line[0]
周圍的引號
跳過前兩行,用wb
模式打開 outfile 而不是w
看看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.