相关疑难解决方法(0)

为什么我的Python代码在从文本文件中读取时会打印额外的字符""?

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")
Run Code Online (Sandbox Code Playgroud)

当逐行打印文件时,代码往往会在前面添加三个不必要的字符,即"".

实际产量:

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.
Run Code Online (Sandbox Code Playgroud)

预期产量:

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 …
Run Code Online (Sandbox Code Playgroud)

python file-handling

22
推荐指数
1
解决办法
2万
查看次数

标签 统计

file-handling ×1

python ×1