0

I have a use case wherein I want to insert data from a list to an existing CSV file, but in the first row of the file. This should push all the other rows from the file to the next ones. Here is what I have attempted so far (which appends the list data at the bottom of the CSV file):

import csv

data = [1,2,3,4,5]
with open("data.csv", "a") as fp:
    wr = csv.writer(fp, dialect='excel')
    wr.writerow(data)

How can I add the data of the given list in the first row of my CSV file using Python?

martineau
  • 119,623
  • 25
  • 170
  • 301
Manas Chaturvedi
  • 5,210
  • 18
  • 52
  • 104
  • https://stackoverflow.com/questions/28162358/append-a-header-for-csv-file-in-python – Dadep Jul 11 '17 at 17:37
  • or https://stackoverflow.com/questions/5914627/prepend-line-to-beginning-of-a-file – somesingsomsing Jul 11 '17 at 17:43
  • You'll need to create a new file with the data you want in it. Afterwards you can delete the original and rename the new file. Alternatively you can read the entire file into memory, then overwrite it with the new row being written first, then the previous contents saved in memory. – martineau Jul 11 '17 at 17:55

0 Answers0