Monday 10 December 2018

python - Write to CSV on first empty line




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)


Answer



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.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...