0

(Python 3.x)So I keep getting a syntax error when reading a file. 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

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:

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
2
  • The syntax error is in the data line from 'p4input.txt' that you are trying to evaluate: you can't evaluate an empty line. eval (and exec) should generally be avoided because they can be a security risk. For details, please see Eval really is dangerous by SO veteran Ned Batchelder. Commented Nov 6, 2017 at 3:27
  • @PM2Ring Oh ok. I see now. Thank you! Commented Nov 6, 2017 at 3:53

1 Answer 1

1

This is happening because when you get to the end of the file, readline() returns an empty string, so you're doing eval(''). You need to check for an empty string and break.

As pointed out in a comment above, you probably shouldn't be using eval. If all your inputs are expected to be integers, you can just use int() instead. You'll still need to check for '' though.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.