我想僅在每一行的第三幀中重寫 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.
你知道如何讓它變得更好嗎?
謝謝
uj5u.com熱心網友回復:
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')
uj5u.com熱心網友回復:
我認為你需要定義你的 CSV 檔案 CSV_File = 'friends.csv
然后打電話with open(CSV_file,'wb') as file:
,你需要洗掉圍繞你的引號line[1] line[0]
跳過前兩行用模式打開輸出檔案wb而不是w
uj5u.com熱心網友回復:
看看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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/339745.html
