将一行数据附加到大型 CSV 文件中的第 2 行

我确信这是一个非常简单的问题,但我似乎找不到任何相关信息。


我有一个非常大的 CSV 文件,我需要在标题后面直接插入一行,这有助于读取 csv 并将其连接到地块 shapefile 的另一个代码。


我有代码来附加我想要的数据行,但它只会转到最后一行。我无法弄清楚如何让代码在标题行之后立即插入我的行。这是我的代码:


import os

import csv


insert_row = '"AAAAAAAAAAAAAAAAAAA","**********","**********","**********","**********","**********","**********","**","**********","**********","****","**********",999999,9999,00'


os.chdir(r"D:\PROPERTY\PINELLAS\Data_20201001_t")



with open("owner_mail.csv", 'r') as csv_file, open("owner_mail.csv", 'a', newline = "") as new_file:

    csv_reader = csv.reader(csv_file)

    csv_writer = csv.writer(new_file)


    csv_writer.writerow(insert_row)

就是这样了。我只需要 insert_row 行数据位于第 2 行位置,而不是位于文件末尾。谢谢。


料青山看我应如是
浏览 91回答 2
2回答

慕尼黑8549860

除非替换完全相同长度的数据,否则不能只在文件中间插入一行。您必须读取整个文件,对其进行编辑,然后重新写入。像这样的东西应该有效:import csv# This must be an iterable not a stringinsert_row = "AAAAAAAAAAAAAAAAAAA","**********","**********","**********","**********","**********","**********","**","**********","**********","****","**********",999999,9999,00with 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 文件不太大而无法完全放入内存,那么您可以一次读取所有行,对其进行编辑,然后将它们写回到同一个文件中。一旦出现问题,风险就更大。更安全地写入新文件,然后删除原始文件并重命名(如果没有错误):import csv# This must be an iterable not a stringinsert_row = "AAAAAAAAAAAAAAAAAAA","**********","**********","**********","**********","**********","**********","**","**********","**********","****","**********",999999,9999,00with open("owner_mail.csv", 'r') as csv_file:    rows = list(csv.reader(csv_file))rows.insert(1,insert_row)  # insert after header rowwith open("owner_mail.csv", 'w') as csv_file:    w = csv.writer(csv_file)    w.writerows(rows)

素胚勾勒不出你

请尝试这个:import osimport csvinsert_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)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python