這個問題在這里已經有了答案: 如何將字串添加到檔案中的每一行? (3 個回答) 23 小時前關閉。
我已經有一個正在訪問的現有 CSV 檔案,我想將資料附加到第一行,但它在檔案末尾寫入資料。
我得到了什么:
![如何將資料添加到 CSV 檔案的現有行?[復制]](https://img.uj5u.com/2022/05/19/5d5eacaf0f9744418c918e7ee0687e1f.png)
但我希望資料像這樣附加:
![如何將資料添加到 CSV 檔案的現有行?[復制]](https://img.uj5u.com/2022/05/19/312cccd4034242f4988aeae9cbd445a2.png)
到目前為止我已經完成的代碼:
import CSV
with open('explanation.csv' , 'a', newline="") as file:
myFile = csv.writer(file)
myFile.writerow(["1"])
uj5u.com熱心網友回復:
您實際上想要做的是用新值替換現有 CSV 檔案中的資料,但是為了更新 CSV 檔案,您必須重寫整個內容。
一種方法是將整個內容讀入記憶體,更新資料,然后使用它來覆寫現有檔案。或者,您可以一次處理檔案并將結果存盤在臨時檔案中,然后在完成全部更新后將原始檔案替換為臨時檔案。
執行后者的代碼如下所示:
import csv
import os
from pathlib import Path
from tempfile import NamedTemporaryFile
filepath = Path('explanation.csv') # CSV file to update.
with open(filepath, 'r', newline='') as csv_file, \
NamedTemporaryFile('w', newline='', dir=filepath.parent, delete=False) as tmp_file:
reader = csv.reader(csv_file)
writer = csv.writer(tmp_file)
# Replace value in the first column of the first 5 rows.
for data_value in range(1, 6):
row = next(reader)
row[0] = data_value
writer.writerow(row)
writer.writerows(reader) # Copy remaining rows of original file.
# Replace original file with updated version.
os.replace(tmp_file.name, filepath)
print('CSV file updated')
uj5u.com熱心網友回復:
您可以讀取整個檔案,將行追加到記憶體中,然后寫入整個檔案:
def append(fname, data):
with open(fname) as f:
reader = csv.reader(f)
data = list(reader) list(data)
with open(fname, 'w') as f:
writer = csv.writer(f)
writer.writerows(data)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/477050.html
標籤:Python python-3.x CSV
