[英]Python can't read log file correctly unless I paste its content in a new text file
I am using open() to read a log file, but I got strange content. 我正在使用open()来读取日志文件,但是内容很奇怪。 If I open the log file by Notepad++, copy the content and paste it in new file, save it as .txt file, open() can read the correct content. 如果我通过Notepad ++打开日志文件,请复制内容并将其粘贴到新文件中,另存为.txt文件,open()可以读取正确的内容。 Code is: 代码是:
with open(a_file, 'r') as my_file:
for line in my_file:
line_number += 1
if line_number == 1060 or line_number == 1061:
print(line)
I tried many methods: 我尝试了很多方法:
You can't read the file because the it's encoded in UTF-16
, you can tell by the first characters which are the BOM . 您无法读取该文件,因为该文件以UTF-16
编码,您可以通过第一个字符BOM来区分。 0xff
is part of the BOM for UTF-16
. 0xff
是UTF-16
的BOM的一部分。 So when reading just add encoding='utf16'
(or use codecs.open
with utf16
in python2) 因此,在阅读时只需添加encoding='utf16'
(或在python2 codecs.open
与utf16
一起使用)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.