为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

料青山看我应如是 2023-09-19 13:49:40
我确信这是一个非常简单的问题,但我似乎找不到任何相关信息。我有一个非常大的 CSV 文件,我需要在标题后面直接插入一行,这有助于读取 csv 并将其连接到地块 shapefile 的另一个代码。我有代码来附加我想要的数据行,但它只会转到最后一行。我无法弄清楚如何让代码在标题行之后立即插入我的行。这是我的代码:import osimport csvinsert_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 行位置,而不是位于文件末尾。谢谢。
查看完整描述

2 回答

?
慕尼黑8549860

TA贡献1818条经验 获得超11个赞

除非替换完全相同长度的数据,否则不能只在文件中间插入一行。您必须读取整个文件,对其进行编辑,然后重新写入。


像这样的东西应该有效:


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 文件不太大而无法完全放入内存,那么您可以一次读取所有行,对其进行编辑,然后将它们写回到同一个文件中。一旦出现问题,风险就更大。更安全地写入新文件,然后删除原始文件并重命名(如果没有错误):


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)


查看完整回答
反对 回复 2023-09-19
?
素胚勾勒不出你

TA贡献1827条经验 获得超9个赞

请尝试这个:


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)


查看完整回答
反对 回复 2023-09-19
  • 2 回答
  • 0 关注
  • 90 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信