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.
with open('data.txt') as f:
for line in f:
value = int(line)
Then you can use the value as needed.
Aside: The advantage of using with to open the file is that it is automatically closed for you when you are done, or an exception is encountered.
To respond to the title of your question, yes you are misunderstanding it. Let me explain:
eval executes the code you place in it. So x=eval('c') is the same as x=c.
raw_input is used to get user input. The parameter is the string to display to the user, not the input.
If you just want to read the values that are in a file, you could use
with open('file') as f:
for line in f:
var = int(line)
if you want to retrieve values from the files then this will do, using eval() for this doesn't make sense:
>>> with open('data.txt') as f:
values=[int(x) for x in f]
>>> values
[2, 3, 2, 3, 1, 0]
Related
I have a text file which has tab delimated data with 2 language translations as follows;
to the regimes thanthrayanta
according to the anuwa
great maha
situation thathwaya
parabraman parabrahman
two of the two dwithwayan
on a matha
depends randa
exist pawathee
he ohu
I am trying to get those data as follows,
# Read the file and split into lines
lines = open('old data/eng-sin.txt' % (lang1, lang2), encoding='utf-8').\
read().strip().split('\n')
But when I run the code, I get an error as ;
TypeError: not all arguments converted during string formatting
As I searched the error I got an answer as the % used is depreciated and new way is to use .formate but still it doesn't solve the issue. Please help to fix this issue
Anyway this wouldn't work since you can have spaces, so for example you would obtain lang1 = 'to' and lang2 = 'the' in the first line.
You could do something like this:
with open('old data/eng-sin.txt', encoding='utf-8') as f:
lines = [ line.split('\t') for line in f ]
There is several errors "a bytes-like object is required, not 'str'. But none of them is related to mine. I open the file using open(filename, "w"), not "wb". The code is like 150 lines long. The beginning of the code is to assign the input of command line into parser args.
The args.result is an empty txt file which I want to write my result onto.
I open it using open.
I think the following code should be enough to illustrate my question. Before the line 65, the code is writing two functions to be used in calculation but I think it should be irrelevant to the bug.
In the code, I manually create the file 'save/results/result.txt' in the command terminal. Then I open the file in the line 132.
The remaining code is
A interesting bug happens that the line 158 runs OK. "begin training\n" can be written into file. Then for the line 165, during the first time of loop, it is OK and "aa\n" can be written into file. But during the second loop, the program end with an error "a bytes-like" object is required, not 'str'. The error message is as following.
Anyone could provide a help of that?
Quite thanks.
I've never had trouble with similar code, but if you want a quick fix, I'd bet making a string named f_text and adding to it within the for loop, then writing all of it to the file after the last iteration of the for loop would be a simple way to circumvent the problem.
IE:
f_text = ""
for epoch in range(your_range):
# Do calculations
print(the_stuff_you_wanted_to)
f_text += the_stuff_you_wanted_to + "\n"
f.write(f_text)
I'm mostly posting this to act as a quick fix though. I feel that there's probably a better solution and could help more if you show more of your code, like where you actually initialize f.
All I am trying to do is get Python to open and read a file I have created. I realize there are many other ways to do this, but I'm just wondering why this isn't working. I have my file saved in the same location as this as well. Does python recognize rec for records? I just watched a tutorial on this so I'm rather confused
with open('Broncos.txt') as fo:
for rec in fo:
print rec
Syntax Error: print rec: <string>, line 6, pos 17
The syntax error you're receiving is most likely due to the lack of parentheses around your print statement (assuming you're using Python 3). A simple change will allow the program to run:
with open('Broncos.txt') as fo:
for rec in fo:
print(rec)
I think that error is in the last line of your code. You need to include parenthesis around rec in last line of your code:
with open('Broncos.txt') as fo:
for rec in fo:
print (rec)
Python 2 vs. Python 3: print
Very trivial, and the change in the print-syntax is probably the most
widely known change, but still it is worth mentioning: Python 2’s
print statement has been replaced by the print() function, meaning
that we have to wrap the object that we want to print in parantheses.
Python 2 doesn’t have a problem with additional parantheses, but in
contrast, Python 3 would raise a SyntaxError if we called the print
function the Python 2-way without the parentheses.
So you'd need to do this:
with open('Broncos.txt') as fo:
for rec in fo:
print(rec)
I am creating a program that stores options in a txt file, and I tried a few different lines but so far I think an eval is the best one.
I got this info in the file:
colordefondo = "#abcdef"
and I got this eval in the program:
for line in open("filename.txt", "r"):
eval(line)
However, when I try the code it gives me this error:
Traceback (most recent call last):
File "D:\project-sae\Sae.py", line 25, in <module>
eval(line)
File "<string>", line 1
colordefondo = "#abcdef"
^
SyntaxError: invalid syntax
My question is Why? And if anyone knows a better way to load and store the value of several options from a txt file it would be great. Nevertheless my question is about why that eval is failing, my knowledge about how eval works seems wrong and I don't know why, used it several times before, just never from a file.
As the documentation says, 'eval' evaluates an expression. Not a statement. Assignments are statements.
You could use the exec statement. But if you want to exec all of the lines of a file, that's exactly what execfile does. (I'm assuming Python 2.x here; things are a little different in 3.x, but the idea is similar.)
However, this is a bad idea to do in the first place. A better way to load and store the value of several options from a txt file is to use anything other than Python source as your format. JSON, .ini files, .rc files, etc. Python comes with code built-in to handle a variety of such formats. See File Formats and Internet Data Handling for a list of the relevant modules, read through them, and pick the one you want.
I have code to read in the version number from a make file.
VERSION_ID=map(int,re.match("VERSION_ID\s*=\s*(\S+)",open("version.mk").read()).group(1).split("."))
This code takes VERSION_ID=0.0.2 and stores it as [0, 0, 2].
Is there any way I can increment this number by one and write the new version number into the version.mk file with the variable VERSION_ID.
Thanks
I have tried the same statement with write() instead of read() but I am getting an error saying that I can not write a list. I have also tried to write it as a string but am getting a bad file descriptor message.
s = str(VERSION_ID)
VERSION_ID=map(int,re.search("VERSION_ID\s*=\s*(\S+)",open("version.mk").write(s)).group(1).split("."))
I know this is rubbish, I just can't seem to find what to do here in the online docs.
I have also tried the pickle module to no avail. Maybe I'd be able to write a pickled list instead and then unpickle it. Or I was thinking I could just write over the whole line altogether.
I've tried to do anther approach, Ihave tried to get list to be entered as a string. I have tried this but I am not sure if it will work.
for x in VERSION_ID:
"VERSION_ID={0}.{1}.{2}.format(x)
perhpas something like this (you should also check for errors and that)
#! /usr/bin/python
import re
fn = "version.mk"
omk = open(fn).readlines()
nmk = open(fn, "w")
r = re.compile(r'(VERSION_ID\s*=\s*)(\S+)')
for l in omk:
m1 = r.match(l)
if m1:
VERSION_ID=map(int,m1.group(2).split("."))
VERSION_ID[2]+=1 # increment version
l = r.sub(r'\g<1>' + '.'.join(['%s' % (v) for v in VERSION_ID]), l)
nmk.write(l)
nmk.close()