名称为sketch1.txt
的文件的内容Man: Is this the right room for an argument?
Other Man: I've told you once.
Man: No you haven't!
Other Man: Yes I have.
Man: When?
Other Man: Just now.
Man: No you didn't!
代码:
try:
def read_file( ):
data = open('C:\\Users\\Adam\\Documents\\eBook\\PythonData\\sketch1.txt', 'r')
print ("---- read all---")
for read_lines in data:
try:
if read_lines.find(':') != -1:
(role, line_said) = read_lines.split(":", 1)
print(role +' says ' +line_said)
else:
print(read_lines)
except:
pass
except:
print("data file is missing")
结果: 工作一次,但不是每次我跑
---- read all---
Man says Is this the right room for an argument?
Other Man says I've told you once.
Man says No you haven't!
Other Man says Yes I have.
错误: 在大多数情况下,我最终只收到一份印刷声明
---- read all---
答案 0 :(得分:2)
您的示例中似乎缺少一些代码。例如,我不明白为什么你可以循环数据而不在for循环的范围内定义它(它只在read_file函数中定义,从不调用)。此外,代码是不必要的复杂,所以除非有任何特定的方式与拆分,我做如下:
with open('C:\\Users\\Adam\\Documents\\eBook\\PythonData\\sketch1.txt', 'r') as f:
for line in f:
print line.replace(':', ' says', 1)
这也将在您完成阅读后关闭文件(由于with语句)。