在 Python 中将换行符写入 csv
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43733205/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Write newline to csv in Python
提问by DIGSUM
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:
我想通过将新的内容行(包括换行符)写入 csv 文件来结束 for 循环的每次交互。我有这个:
# 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:
这似乎没有写入实际的 \n (换行符)文件。更远:
# 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.
我也尝试过,outfile.write(os.linesep)
但没有奏效。
采纳答案by fuwiak
change 'w' to 'a'
将“w”更改为“a”
with open('outfile.csv','a')
回答by Chankey Pathak
with open('outfile.csv', 'w', newline='') as f:
f.writerow(...)
Alternatively:
或者:
f = csv.writer('outfile.csv', lineterminator='\n')
回答by Lee Ran
I confront with same problem, only need follow:
我遇到同样的问题,只需要遵循:
f = csv.writer('outfile.csv', lineterminator='\n')