Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ssis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在不替换现有内容的情况下向.csv文件BOF添加行_Python_Csv - Fatal编程技术网

Python 如何在不替换现有内容的情况下向.csv文件BOF添加行

Python 如何在不替换现有内容的情况下向.csv文件BOF添加行,python,csv,Python,Csv,当我需要向.csv文件添加新行时,我尝试了以下脚本。 文件='test.csv' with open(file,'r+',newline='') as csvfile: row = ['hello,world\r\n'] csvfile.writelines(row) 然后我检查了.csv文件,发现第一行已经更改 你好,世界 ,1,33,1,1,2,0107107,52,5,20,12,19,32,52,23,4,42,0,5,3,3,4,3,0,1,0,1,2,0 33955

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

with open(file,'r+',newline='') as csvfile:
    row = ['hello,world\r\n']
    csvfile.writelines(row)
然后我检查了.csv文件,发现第一行已经更改

你好,世界

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

339558,69428,1,15,1,0,0,0,01804,41,3,6,4,10,18,41,10,1,20,0,2,0,4,3,1,0,0,0,1,1,0

3379411,3465,1,0,0,3,0,01901,28,2,1,4,9,7,28,5,1,12,0,1,1,2,0,1,0,0,1,2,1,0


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

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


您必须先读取文件,在读取文本前加上新行,然后将所有内容写入文件

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)

不能,只能附加到文件。方法是打开一个新文件,写入新记录,然后将原始文件中的剩余记录读写到新文件中。这在任何语言中都是一样的。谢谢,这对我来说似乎是可以接受的,但是你知道有没有更优雅的方法来管理它吗?据我所知没有。谢谢,我明白了,在python中没有插入文件的方法。不管怎样,请欣赏。@yuyuqian:在任何语言中都没有这种方式,这是文件系统工作方式的一个特点。