[英](Python 3.x)Syntax Error EOF while parsing when reading a line from a file.
(Python 3.x)So I keep getting a syntax error when reading a file. (Python 3.x)因此,在读取文件时,我总是收到语法错误。 I've had this problem for a while now.
我已经有一段时间这个问题了。 I've been working on other parts of the program so far(not shown), but can't solve this syntax error.
到目前为止,我一直在研究程序的其他部分(未显示),但无法解决此语法错误。 I am very confused.
我很困扰。 I feel guilty posting about a syntax error but I am out of ideas.
关于语法错误,我感到内,但我没有主意。
Here is the error: Syntax Error: unexpected EOF while parsing: , line 0, pos 0 @ line 8 这是错误:语法错误:解析时出现意外的EOF:第8行,第0行,pos 0
Code: 码:
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()
The input file (p4input.txt) Has the following data: 输入文件(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
This is happening because when you get to the end of the file, readline()
returns an empty string, so you're doing eval('')
. 发生这种情况是因为,当您到达文件末尾时,
readline()
返回一个空字符串,因此您正在执行eval('')
。 You need to check for an empty string and break
. 您需要检查一个空字符串并
break
。
As pointed out in a comment above, you probably shouldn't be using eval
. 正如上面评论中指出的那样,您可能不应该使用
eval
。 If all your inputs are expected to be integers, you can just use int()
instead. 如果所有输入均应为整数,则可以使用
int()
代替。 You'll still need to check for ''
though. 不过,您仍然需要检查
''
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.