(Python 3.x)因此,在读取文件时,我总是收到语法错误。我已经有一段时间这个问题了。到目前为止,我一直在研究程序的其他部分(未显示),但无法解决此语法错误。我很困扰。
关于语法错误,我感到内,但我没有主意。
这是错误:语法错误:解析时出现意外的EOF:第8行,第0行,pos 0
码:
def main():
filename = 'p4input.txt'
infile = open(filename, "r")
command = 0
while command != 3 and command < 3:
command = eval(infile.readline()) #Problem here
convert = eval(infile.readline())
print(command)
print(convert)
print("done")
main()
输入文件(p4input.txt)
具有以下数据:
2
534
1
1101
Complete traceback:
Traceback (most recent call last):
File "C:/Users/Ambrin/Desktop/CS 115/TESTER.py", line 16, in <module>
main()
File "C:/Users/Ambrin/Desktop/CS 115/TESTER.py", line 8, in <module>
command = eval(infile.readline())
File "<string>", line 0, in ?
Syntax Error: unexpected EOF while parsing: <string>, line 0, pos 0
最佳答案
发生这种情况是因为,当您到达文件末尾时,readline()
返回一个空字符串,因此您正在执行eval('')
。您需要检查一个空字符串和break
。
正如上面评论中指出的那样,您可能不应该使用eval
。如果所有输入均应为整数,则可以使用int()
代替。不过,您仍然需要检查''
。
关于python - (Python 3.x)语法从文件中读取一行时解析时出现EOF错误。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47129292/