Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write newline to csv in Python

I want to end each interation of a for loop with writing a new line of content (including newline) to a csv file. I have this:

# Set up an output csv file with column headers
with open('outfile.csv','w') as f:
    f.write("title; post")
    f.write("\n")

This does not appear to write an actual \n (newline) the file. Further:

    # Concatenate into a row to write to the output csv file
    csv_line = topic_title + ";" + thread_post
    with open('outfile.csv','w') as outfile:
                 outfile.write(csv_line + "\n")

This, also, does not move the cursor in the outfile to the next line. Each new line, with every iteration of the loop, just overwrites the most recent one.

I also tried outfile.write(os.linesep) but did not work.

like image 368
DIGSUM Avatar asked May 02 '17 08:05

DIGSUM


2 Answers

change 'w' to 'a'

with open('outfile.csv','a')
like image 95
fuwiak Avatar answered Oct 03 '22 07:10

fuwiak


with open('outfile.csv', 'w', newline='') as f:
    f.writerow(...)

Alternatively:

f = csv.writer('outfile.csv', lineterminator='\n')
like image 32
Chankey Pathak Avatar answered Oct 03 '22 08:10

Chankey Pathak