【问题标题】:Writing to a mac csv not working using python file writter使用python文件编写器写入mac csv不起作用
【发布时间】:2016-09-29 18:09:53
【问题描述】:

我有一个 python 代码,它比较两个文件并返回公共行并将它们写入结果文件。我使用的是 MAC 机器。

脚本.py

with open('temp1.csv', 'r') as file1:
    with open('serialnumbers.txt', 'r') as file2:
        same = set(file1).intersection(file2)
        print same

with open('results.csv', 'w') as file_out:
    for line in same:
        file_out.write(line)
        print line

temp1.csv

M11435TDS144
M11543TH4292
SN005
M11509TD9937
M11543TH4258
SN005
SN006
SN007

序列号.txt

G1A114042400571
M11251TH1230
M11543TH4258
M11435TDS144
M11543TH4292
M11509TD9937

以上脚本在mac上的输出是

设置([])

如果我在 Windows 上运行相同的脚本,它工作正常。我发现这是mac上的一个csv问题。我该如何解决这个问题?

【问题讨论】:

  • 如果是 Windows 上的 CSV 文件,则使用“\r\n”分隔符。我假设一个文件有“\r\n”而另一个只有“\n”。你能检查一下吗?
  • 在 Mac 上测试,得到的输出与您描述的不同...
  • 试试:same = set(l.strip() for l in file1).intersection(l.strip() for l in file2)
  • 能否请您在每个临时文件和序列号文件中添加一个额外的新行并再次测试 - 谢谢
  • 这是哪个python版本?

标签: python macos csv line-breaks file-writing


【解决方案1】:

两个文件的结束分隔符不同。

  • .csv 文件可能有 Windows 行尾:“\r\n”,
  • .txt 文件可能有 Posix 行尾:“\n”。

因此,在二进制模式下,行总是不同的。

你应该在文本模式下阅读这两个文件,像这样:

import io

with io.open('temp1.csv', 'r') as file1:
    with io.open('serialnumbers.txt', 'r') as file2:
        same = set(file1).intersection(file2)
        print(same)

你会得到:

set([u'M11543TH4258\n', u'M11509TD9937\n', u'M11543TH4292\n', u'M11435TDS144\n'])

另请注意,CSV 文件通常使用 ISO-8859-1 或 cp1252 编码(Windows 的旧编码)进行编码。

删除换行符

with io.open('temp1.csv', 'r') as file1:
    with io.open('serialnumbers.txt', 'r') as file2:
        same = set(line.strip() for line in file1).intersection(line.strip() for line in file2)
        print(same)

【讨论】:

  • 那么您需要重新添加换行符以保持一致性。
  • 谢谢你,laurent..这有帮助..但是当我将它写入结果文件时,它会全部写入同一行。
  • @KrishnaPrasad:所以使用第一个解决方案:不要剥离线条……
猜你喜欢
  • 2021-02-03
  • 2012-08-06
  • 2020-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-23
  • 1970-01-01
相关资源
最近更新 更多