Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write to CSV on first empty line [duplicate]

I'm developing an application to write lines to a CSV. However, when I run the application a second time, the line that was already written is overwritten with the new line. How can I make it so that the writer writes to the next blank line, not one that already has data in it? I haven't found anything on how to do this. Here's my code below:

listsof = [1, 2, 3, 4]
with open('C:/Users/Family3/Downloads/weather.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile, delimiter=',',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)
    writer.writerow(listsof)
like image 845
hichris123 Avatar asked Dec 26 '13 21:12

hichris123


People also ask

Why csv writer adds blank rows?

Why csv writer adds blank rows? The way Python handles newlines on Windows can result in blank lines appearing between rows when using csv. writer . In Python 2, opening the file in binary mode disables universal newlines and the data is written properly.

Is it necessary to have a line as first line in CSV file?

The first row is only mandatory when the import template has the setting use "Use column headers as configuration" enabled. However having the first row in the CSV file helps knowing what data is in the file.

How do I skip the first row in a CSV file?

with open("mycsv. csv", "r") as csvfile: csvreader = csv. reader(csvfile) # This skips the first row of the CSV file.


2 Answers

Try this instead (note the 'a' for append):

with open('C:/Users/Family3/Downloads/weather.csv', 'a', newline='') as csvfile:
    writer = csv.writer(csvfile, delimiter=',',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)
    writer.writerow(listsof)

The 'a' opens the file for appending and does not erase the already existing file with the same name.

like image 51
Justin O Barber Avatar answered Sep 20 '22 01:09

Justin O Barber


It is because, whenever you open your csv file, you never take into account that you might already have data in your file. When you load your csvfile into your program, you should append your new data to the file instead of just writing to it.

like image 31
Dyrborg Avatar answered Sep 21 '22 01:09

Dyrborg