【发布时间】:2016-03-27 17:36:25
【问题描述】:
try:
data=open('info.txt')
for each_line in data:
try:
(role,line_spoken)=each_line.split(':',1)
print(role,end='')
print(' said: ',end='')
print(line_spoken,end='')
except ValueError:
print(each_line)
data.close()
except IOError:
print("File is missing")
在逐行打印文件时,代码往往会在前面添加三个不必要的字符,即“”。
实际输出:
Man said: Is this the right room for an argument?
Other Man said: I've told you once.
Man said: No you haven't!
Other Man said: Yes I have.
预期输出:
Man said: Is this the right room for an argument?
Other Man said: I've told you once.
Man said: No you haven't!
Other Man said: Yes I have.
【问题讨论】:
-
您的文件可能以 UTF-8 和 BOM 编码。如果这不是您想要的,请在没有 BOM 的情况下对其进行编码。
-
@MarcB 不是骗人的; Python 不是 PHP,在处理 UTF-8 BOM 方面有更好的选择。 OP,将
encoding='utf-8-sig'传递给您的open()呼叫。 -
是的,文森特是对的。这是Byte-order mark 的典型情况。
-
@senshin 成功了,谢谢。 'code' data=open('sketch.txt',encoding='utf-8-sig')
标签: python file-handling