【问题标题】:Python writing unrecognizable characters at end of linePython在行尾写入无法识别的字符
【发布时间】:2016-11-21 01:56:44
【问题描述】:

我使用的是 windows7 机器,但我无法弄清楚为什么 Python 3 在每行末尾都写了这个字符 ਍ഀ

这是我的代码:

import csv

input_file = open('7.15.16.txt', 'r')
output_file = open('no_commas1.csv', 'w')
for line in input_file:
    line = line.replace(",", " ")
    output_file.write(line)
output_file.close()
input_file.close()

【问题讨论】:

  • 我唯一能想到的:检查编码,您也可以尝试使用特定编码打开文件:f = open(fname, encoding="utf-8")。
  • 我相信那些是newline symbols'\r\n'。它会导致哪些问题?你有原始文件吗?
  • 它们不在原始文件中。我也无法使用 encoding="utf-8" 打开文件 - 我收到错误消息。

标签: python-3.x csv character


【解决方案1】:
input_file = open('7.15.16.txt', 'r', encoding='utf16')

【讨论】:

    【解决方案2】:

    好的,你有一个 .txt 文件。所以要在 .txt 文件中定义一个新行 \r\n 使用符号。如果您在文本编辑器中打开它,您将看不到它们。您必须打开隐形字符模式。您可以使用notepad++ 来查看它们。

    然后将信息保存在 .csv 文件中。但是 .csv 对于\r\n 符号没有特殊含义。结果,它们按原样显示。

    您必须直接删除代码中的\r\n 符号。见this issue

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-26
      • 2020-12-18
      • 2018-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多