2017-06-03 57 views
0

当我需要将一行添加到.csv文件时,我尝试了以下脚本。 文件=“test.csv”如何将行添加到.csv文件BOF无需替换存在的东西

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

我想知道ca n我在.csv文件的开头添加一个新行而不更改存在的元素?寻求()?请帮助我,我真的很感激它!

+2

您不能,只能附加到文件。做到这一点的方法是打开一个新文件,写入新记录,然后从原始文件读取+写入剩余记录到新记录。顺便说一句,任何语言都是一样的。 – cdarke

回答

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) 
+0

谢谢,这对我来说似乎是可以接受的,但是你知道有没有更好的方法来管理它? – Yochega

+0

据我所知不。 –

+0

好吧,无论如何thx!你帮忙了 – Yochega

0

csv是一个文本文件。为了按照建议的方式更新文本文件,必须先在文本文件中读取文本文件,然后编写标题,然后编写新行,然后编写旧文件行值。

How do I modify a text file in Python?

+0

谢谢,我明白,没有这种方式插入到Python中的文件。无论如何,感激它。 – Yochega

+0

@yuyuqian:在任何*语言中都没有这种方式,这是文件系统工作方式的一个特点。 – cdarke

相关问题