Python Forum

Full Version: Prepend Row to CSV file.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

I am brand new to Python programming, but I have successfully manage to bodge together a script using my previous coding knowledge and some frantic Googling.

Part of the code appends a line of information to a local CSV file, and is shown below

with open('c:\power\powerdata.csv', 'a') as csvFile:
    writer = csv.writer(csvFile)
    writer.writerow(row)
csvFile.close()
I really need the line to be added at the start of the file and not at the end, as this code does. This is where I am stuck. None of my Googling has given an clean solution.

Can someone please give me a similarly elegant solution to add the row to the start of the file.

Thanks muchly!

K.
AFAIK, you will have to rewrite the file or write a new file. To rewrite, you would read the whole file into a data structure (like a list of rows), add the new row to the beginning, and then write everything back to the original file. Alternatively you could start a new file, write the new row to that file, then read each row from the new file and add it to the new file. This would be good if the file is large.

Why do you need to add it to the beginning of the file? Given how much easier it is to add to the end of the file it seems an odd way to set things up.
Hey, thanks for the reply.

The reason I wanted to add data at the start was I waned to plot the last 24 data points on a graph. There was a limitation of the graphing plugin that it you can only list a specific range of data, rather than specify the last x rows. If I had put the data in top down, I could just specify the first 24 rows to get the newest data.

After you said that it is more complex to add data at the start, I just changed the Python script to append the data on the end, then write a second file which is an extract of the last 24 lines. I can now graph all data and the last 24 points separately.

Thanks for your help.