在Python中用csv写新行

DIG*_*SUM 6 python csv file-io

我想结束一个for循环的每个interation,并将一行新内容(包括换行符)写入csv文件.我有这个:

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

这似乎没有写出实际的\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")
Run Code Online (Sandbox Code Playgroud)

这也不会将outfile中的光标移动到下一行.每个循环的每次迭代都会覆盖最新的一行.

我也试过outfile.write(os.linesep)但没有奏效.

fuw*_*iak 6

将'w'改为'a'

with open('outfile.csv','a')
Run Code Online (Sandbox Code Playgroud)

  • 为什么会这样?您能否解释一下更改访问修饰符如何更改EOL字符?为什么不写('\ n')工作? (2认同)

Cha*_*hak 5

with open('outfile.csv', 'w', newline='') as f:
    f.writerow(...)
Run Code Online (Sandbox Code Playgroud)

或者:

f = csv.writer('outfile.csv', lineterminator='\n')
Run Code Online (Sandbox Code Playgroud)