0

when I need to add a new line to a .csv file, I tried this following scripts. file = 'test.csv'

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

then I check the .csv file, found out that the fist line has been changed.

hello,world

,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

I wonder how can I add a new line in the beginning of a .csv file without changing the exist elements? Seek()? please help me, I really appreciate it!!!

Yochega
  • 15
  • 3
  • 2
    You can't, you can only append to a file. The way to do this is to open a new file, write the new record, then read+write the remaining records from the original file to the new one. That would be the same in any language by the way. – cdarke Jun 03 '17 at 08:43

2 Answers2

1

You will have to read the file first, prepend the new line to the read text, and write everything to the file.

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

This will load the whole file to memory, and if the file is really big this could be a problem. A solution would be to write to a different file and read the source file line by line:

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)
Paco H.
  • 2,034
  • 7
  • 18
0

A csv is a text file. In order to update the text file in the way you suggest you would have to read in the text file first, then write the header, then write your new line, then write the old files row values.

How do I modify a text file in Python?

FredMan
  • 861
  • 7
  • 19
  • thanks, i see, there is no such way to insert into a file in python. Anyway, appreciate it. – Yochega Jun 03 '17 at 09:37
  • @yuyuqian: there is no such way in *any* language, it is a feature of the way file-systems work. – cdarke Jun 03 '17 at 10:04