2 回答

TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超11個(gè)贊
除非替換完全相同長(zhǎng)度的數(shù)據(jù),否則不能只在文件中間插入一行。您必須讀取整個(gè)文件,對(duì)其進(jìn)行編輯,然后重新寫入。
像這樣的東西應(yīng)該有效:
import csv
# This must be an iterable not a string
insert_row = "AAAAAAAAAAAAAAAAAAA","**********","**********","**********","**********","**********","**********","**","**********","**********","****","**********",999999,9999,00
with open("owner_mail.csv", 'r') as csv_file, open("owner_mail_updated.csv", 'w', newline = "") as new_file:
csv_reader = csv.reader(csv_file)
csv_writer = csv.writer(new_file)
header = next(csv_reader)
csv_writer.writerow(header)
csv_writer.writerow(insert_row)
for line in csv_reader:
csv_writer.writerow(line)
如果 CSV 文件不太大而無(wú)法完全放入內(nèi)存,那么您可以一次讀取所有行,對(duì)其進(jìn)行編輯,然后將它們寫回到同一個(gè)文件中。一旦出現(xiàn)問(wèn)題,風(fēng)險(xiǎn)就更大。更安全地寫入新文件,然后刪除原始文件并重命名(如果沒(méi)有錯(cuò)誤):
import csv
# This must be an iterable not a string
insert_row = "AAAAAAAAAAAAAAAAAAA","**********","**********","**********","**********","**********","**********","**","**********","**********","****","**********",999999,9999,00
with open("owner_mail.csv", 'r') as csv_file:
rows = list(csv.reader(csv_file))
rows.insert(1,insert_row) # insert after header row
with open("owner_mail.csv", 'w') as csv_file:
w = csv.writer(csv_file)
w.writerows(rows)

TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超9個(gè)贊
請(qǐng)嘗試這個(gè):
import os
import csv
insert_row = '"AAAAAAAAAAAAAAAAAA","**********","**********","**********","**********","**********","**********","**","**********","**********","****","**********",999999,9999,00'
with open("owner_mail.csv", 'r') as csv_file, open("owner_mail.csv", 'w') as new_file:
csv_reader = csv.reader(csv_file)
reader = list(csv_reader)
reader.insert(1,insert_row)
csv_writer = csv.writer(new_file)
csv_writer.writerows(reader)
添加回答
舉報(bào)