【问题标题】:Why does Python not read the end of line character when opening utf-16 file?为什么 Python 在打开 utf-16 文件时不读取行尾字符?
【发布时间】:2019-06-21 06:27:19
【问题描述】:

我正在连接两个文本文件,一个是 utf-16。从文件中读取行并拆分它们时,utf-16 文件没有行尾。一切都在一行中,所以我必须指定一个行尾字符。任何想法为什么?

下面的代码可以运行,但我想知道为什么我需要为 utf-16 设置行尾。

with open(file_temp, 'w') as outfile:
    with open(file_normal) as infile:
        for line in infile:
            outfile.write(line.split(",")[0]) # auto end of line
    with open(file_utf16, encoding='utf-16') as infile: # different file format
        for line in infile:
            outfile.write(line.split(",")[0] + "\n") # needs end of line char for some reason ?

当使用正确的编码读取时,我希望 utf-16 文件中出现行尾字符。

【问题讨论】:

  • 是的,我的错误,file_normalsplit 范围包括 行尾,而 file_utf16split 范围不包括 行尾.

标签: python utf-16


【解决方案1】:

换行符与编码无关

with open("someFile_utf16.txt", "w",encoding='utf-16') as infile:
    for x in range(10):
        infile.write(str(x))

with open("someFile_normal.txt", "w") as infile:
    for x in range(10):
        infile.write(str(x))

文件中的数据相同

0123456789

唯一可能的解释是普通文件中写入了行尾,而utf-16文件没有

更多参考

https://docs.python.org/3/tutorial/inputoutput.html

【讨论】:

  • 感谢您的澄清。两个文件都有行尾,但我错误地认为split会忽略行尾而只查看文本,而write会生成end行数.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-07-20
  • 2012-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-17
  • 1970-01-01
相关资源
最近更新 更多