0

Is there a way to append data to the beginning(first line) of a csv file without reading the whole file into memory? The file is huge and all I am trying to add is a header record to the file.

import csv 
csv = open(csv, 'a')
csv.write(header_record)
csv.close()
  • 1) Create a new file with your header; 2) Append the old file to the new file; 3) Rename the new file to what you want (like the old file's name); 4) Delete the old file. There is really no other way... – dawg Oct 02 '20 at 16:23
  • Basically, make a new file, write the new line, iterate over the original and write each to the new file. If you search you will find **many** SO Q&A's related to your question - I'm sure one or more fits your circumstance; pick one and we'll mark your question as a duplicate. – wwii Oct 02 '20 at 16:25
  • You can open a file in "append" mode, but the file pointer is at the end of the file. Unfortunately the way mentioned above is the best way IMO. – whege Oct 02 '20 at 16:25
  • Open the file in append mode, use `seek(0)` to point to the beginning of the file and then write the header. – PApostol Oct 02 '20 at 16:27

1 Answers1

0

You should use pandas to read csv, add the new column, sort columns and save a new file using to_csv method