【问题标题】:How to add line to a .csv file BOF without replacing exist things如何在不替换现有内容的情况下向 .csv 文件 BOF 添加行
【发布时间】:2017-11-04 15:20:42
【问题描述】:

当我需要向 .csv 文件添加新行时,我尝试了以下脚本。 文件 = 'test.csv'

with open(file,'r+',newline='') as csvfile:
    row = ['hello,world\r\n']
    csvfile.writelines(row)

然后我检查 .csv 文件,发现第一行已更改。

你好,世界

,1,33,1,1,2,0,107,107,52,5,20,12,19,32,52,23,4,42,0,5,3,3,4,3,0, 1,0,1,1,2,0

339,558,69,428,1,15,1,0,0,0,0,1804,41,3,6,4,10,18,41,10,1,20,0,2,0,4 ,3,1,0,0,0,1,1,1,0

3379,411,3,465,1,0,0,0,3,0,0,1901,28,2,1,4,9,7,28,5,1,12,0,1,1 ,2,0,1,0,0,0,1,2,1,0

我想知道如何在不更改现有元素的情况下在 .csv 文件的开头添加新行?寻找()?请帮帮我,我真的很感激!!!

【问题讨论】:

  • 你不能,你只能追加到一个文件。这样做的方法是打开一个新文件,写入新记录,然后将原始文件中的剩余记录读+写到新文件中。顺便说一句,这在任何语言中都是一样的。

标签: python csv


【解决方案1】:

您必须先读取文件,将新行添加到读取的文本中,然后将所有内容写入文件。

with open('data.csv', mode='r+') as csvfile:
    text = csvfile.read()
    text = '1,2,3\n' + text
    csvfile.seek(0)
    csvfile.write(text)

这会将整个文件加载到内存中,如果文件真的很大,这可能是个问题。一种解决方案是写入不同的文件并逐行读取源文件:

new_line = '1,2,3\n'

with open('data1.csv', mode='w') as outfile:
    # Write new line
    outfile.write(new_line)

    # Read lines of source file and write them to the new file
    with open('data.csv', mode='r') as infile:
        for line in infile:
            outfile.write(line)

【讨论】:

  • 谢谢,这对我来说似乎可以接受,但是你知道有没有更优雅的方法来管理这个?
  • 据我所知没有。
【解决方案2】:

csv 是一个文本文件。为了以您建议的方式更新文本文件,您必须先读取文本文件,然后写入标题,然后写入新行,然后写入旧文件行值。

How do I modify a text file in Python?

【讨论】:

  • 谢谢,我明白了,没有这样的方法可以在 python 中插入文件。无论如何,感谢它。
  • @yuyuqian:任何语言中都没有这种方式,它是文件系统工作方式的一个特点。
猜你喜欢
  • 2015-10-11
  • 1970-01-01
  • 2018-10-22
  • 2013-07-12
  • 1970-01-01
  • 2018-08-01
  • 1970-01-01
  • 2019-05-12
  • 2011-06-03
相关资源
最近更新 更多