当我需要在.csv文件中添加新行时,我尝试了以下脚本。 file ='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文件的开头添加新行?寻求()?请帮帮我,我真的很感激!!!!
答案 0 :(得分:1)
您必须先读取文件,将新行添加到读取文本中,然后将所有内容写入文件。
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)
这会将整个文件加载到内存中,如果文件非常大,这可能是个问题。解决方案是写入不同的文件并逐行读取源文件:
for
答案 1 :(得分:0)
csv是一个文本文件。为了以您建议的方式更新文本文件,您必须首先读取文本文件,然后编写标题,然后编写新行,然后写入旧文件行值。