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()
4
  • 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... Commented Oct 2, 2020 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. Commented Oct 2, 2020 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. Commented Oct 2, 2020 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. Commented Oct 2, 2020 at 16:27

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

1 Comment

OP wants to add a header, not a column.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.