Write newline to csv in Python

本小妞迷上赌 提交于 2020-06-25 09:01:21

问题


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.


回答1:


change 'w' to 'a'

with open('outfile.csv','a')



回答2:


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

Alternatively:

f = csv.writer('outfile.csv', lineterminator='\n')



回答3:


I confront with same problem, only need follow:

  f = csv.writer('outfile.csv', lineterminator='\n')


来源:https://stackoverflow.com/questions/43733205/write-newline-to-csv-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!