Working with Python 2.6 and receiving an annoying error, and I’m still unsure why. My file of interest contains multiple lines of only a single value. I want to retrieve these values. This snippet of code
f = open(file, 'r')
for line in file:
value = eval(line)
results in the following error message:
File "<string>", line 1, in <module>
NameError: name 'c' is not defined
So I researched here on Stack Overflow.. with this question and another one.. but I’m having trouble drawing connections between their problems and mine. What I got from them is that my use of eval() may be confusing Python and I should use raw_input to let Python know that it doesn’t have to evaluate line but rather the actual variables line represents. However, fixing my code to be:
for line in file:
value = eval(raw_input(line))
Which kicked out the following error (and may have overloaded terminal.. it simply froze up until I quit the program):
File "<string>", line 0
^
SyntaxError: unexpected EOF while parsing
What am I doing wrong here? I’ve picked up the fact that eval() isn’t the favorite to use around SO, am I misunderstanding it’s function?
EDIT: My file is a list of values so,
2
3
2
3
1
0
etc
EDIT So it was a misunderstanding. Thank you to DSM for pointing out my file names being mismatched and to Levon for still helping out and showing int as a better alternative to eval.
If you just want to read those numbers from a file and convert them to integers this will do.
Then you can use the value as needed.
Aside: The advantage of using
withto open the file is that it is automatically closed for you when you are done, or an exception is encountered.