【问题标题】:Write newline to csv in Python在 Python 中将换行符写入 csv
【发布时间】:2017-09-29 16:49:13
【问题描述】:

我想通过将新的内容行(包括换行符)写入 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")

这似乎不会在文件中写入实际的 \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")

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

我也尝试了outfile.write(os.linesep),但没有成功。

【问题讨论】:

    标签: python csv file-io


    【解决方案1】:

    把'w'改成'a'

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

    【讨论】:

    • 为什么会这样?您能解释一下更改访问修饰符如何改变 EOL 字符吗?为什么 write('\n') 不起作用?
    • 我认为 OP 在循环中打开/关闭文件(他们提到了一个循环但没有显示它在哪里),所以以附加模式打开是一个“修复”,但是 错误的方式.
    • 是的,这是一种解决方法,而不是解决方案。
    【解决方案2】:
    with open('outfile.csv', 'w', newline='') as f:
        f.writerow(...)
    

    或者:

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

    【讨论】:

      【解决方案3】:

      我遇到同样的问题,只需要关注:

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

      【讨论】:

        【解决方案4】:

        如果你使用python2,那么使用

        with open('xxx.csv', 'a') as f:
            writer = csv.writer(f)
            writer.writerow(fields)
        

        如果您使用的是 python3,请使用newline=''

        【讨论】:

          【解决方案5】:

          请尝试:open(output_file_name.csv, 'a+', newline='') as f:

          【讨论】:

            猜你喜欢
            • 2019-03-01
            • 2017-04-29
            • 2021-10-23
            • 1970-01-01
            • 2014-06-06
            • 2017-06-17
            • 2018-05-15
            • 1970-01-01
            • 2012-08-27
            相关资源
            最近更新 更多