Python3 DictWriter 在 Linux 上使用 CRLF 而不是 LF

标签 python linux python-3.x

问题:

在 Python 3 中,我使用 csv.DictWriter 向现有文件追加一行。但是,正在使用 CRLF 行结尾而不是预期的 LF 行结尾。

代码示例:

#!/usr/bin/env python3
import csv

with open("test.csv", 'a', newline='') as test_f:
    test_csv = csv.DictWriter(test_f, delimiter='|', fieldnames=['1', '2'])
    test_csv.writerow({'1': "test1", '2': "test2"})

预期结果:

$ cat -e test.csv
test1|test2$

实际结果:

$ cat -e test.csv
test1|test2^M$

注意事项:

  • 现有文件的文件格式是“unix”,而不是“dos”。
  • 我试过设置newline为 None(默认值)和 '\n'(即使这应该是不必要的,因为默认值是 os.linedep,在 Linux 上已经是 '\n'),但结果是一样的。

最佳答案

通过指定 lineterminator , 你可以控制它。

test_csv = csv.DictWriter(
    test_f,
    delimiter='|',
    lineterminator='\n',  # <--------
    fieldnames=['1', '2'])

关于Python3 DictWriter 在 Linux 上使用 CRLF 而不是 LF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25591756/

相关文章:

python - 如何使用 suds (Python) 对 HTTP 代理进行身份验证?

python - 在python中对具有浮点值的列进行排序

linux - 在 Linux 上映射 ARM 全局定时器

linux - 分段寄存器使用

python - 将 methodcaller 和 attrgetter 与排序相结合

python-3.x - 如何修复Windows上的错误:"AttributeError: module 'tensorflow'没有属性 'contrib'

python - 打印一系列列对齐的列表

python - 推特 Bootstrap href 按钮不起作用

linux - 为什么 zsh 不会自动完成自定义创建的脚本,而 bash 会自动完成?

python - 子进程打开超时实时输出