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)
Related
I'm trying to read a log file, written line by line, via readline.
I'm surprised to observe the following behaviour (code executed in the interpreter, but same happens when variations are executed from a file):
f = open('myfile.log')
line = readline()
while line:
print(line)
line = f.readline()
# --> This displays all lines the file contains so far, as expected
# At this point, I open the log file with a text editor (Vim),
# add a line, save and close the editor.
line = f.readline()
print(line)
# --> I'm expecting to see the new line, but this does not print anything!
Is this behaviour standard? Am I missing something?
Note: I know there are better way to deal with an updated file for instance with generators as pointed here: Reading from a frequently updated file. I'm just interested in understanding the issue with this precise use case.
For your specific use case, the explanation is that Vim uses a write-to-temp strategy. This means that all writing operations are performed on a temporary file.
On the contrary, your scripts reads from the original file, so it does not see any change on it.
To further test, instead of Vim, you can try to directly write on the file using:
echo "Hello World" >> myfile.log
You should see the new line from python.
for following your file, you can use this code:
f = open('myfile.log')
while True:
line = readline()
if not line:
print(line)
I run a script with the code to open a file and it returns SyntaxError. The script is an open source script that I want to test.
with open(f"/home/mine/myfoldr/myapp.yml", "r") as file:
The line above returns the following error:
File "./startup.py", line 28
with open(f"/home/mine/myfoldr/myapp.yml", 'r') as file:
^
I just don't understand what does it mean with f" here, after open(f"...). Because normally it will be write something like below, without f.
with open("/home/mine/myfoldr/myapp.yml", "r") as file:
I think its not a typo because other line code in the script also..have the same style f, for example:
print(f"Which section do you want to change?"
f"[Application/Controller/Database]")
The f at the start of strings is called f-string, introduced with PEP 489 starting at Python 3.6.
It is used for string formatting, similar to .format(). There are a lot of tutorials on it you can read. The basic example:
x = 22
print('this is {}'.format(x))
print(f'this is {x}')
Here, both lines will output the same resulting string this is 22.
You probably get the error because you are using a version older than Python 3.6, some version where f-strings are not supported.
To test the third-party code you will have to use a newer Python version or modify the code yourself (but this last options may be a lot of work and may introduce some unintentional errors).
The section of coding I've written is as such:
thing=9
text_file=open("something.txt", "a")
text_file.write("\n", str(thing))
text_file.close()
This always returns the error Type error: "write" only takes 1 argument. 2 given.
What I'm trying to do is that each time I run this code it writes on a new line rather than the same line. Right now, if this doesn't work, I'm a bit confused how to do this. Any help would be appreciated!
Add a newline to the end1 of the string with the + operator:
text_file.write(str(thing) + "\n")
1Note: If you add it to the front, you will get a blank line at the top of your file, which may not be what you want.
The python interpreter is correct in saying:
"write" only takes 1 argument. 2 given
Python's file methods are documented here.
All you need to be doing is concatenating your string with the newline character. You can do so by replacing:
text_file.write("\n", str(thing))
with:
text_file.write("\n" + str(thing))
This will write an empty line before writing out what you want. This might not be what you are looking for. Instead you can do:
text_file.write(str(thing) + '\n')
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]
I am trying to read from one file and write to another file using:
with open('example2') as inpf, open('outputrt','w') as outf:
for l in inpf:
outf.write(l)
But I am getting a syntax error at the line 1 i.e.
"with open('example2') as inpf, open('outputrt','w') as outf:" pointing at "inpf,"
My python version is 2.6. Is there an error in syntax?
That syntax is only supported in 2.7+.
In 2.6 you can do:
import contextlib
with contextlib.nested(open('example2'), open('outputrt','w')) as (inpf, outf):
for l in inpf:
outf.write(l)
Or it might look cleaner to you to do this (this would be my preference):
with open('example2') as inpf:
with open('outputrt','w') as outf:
for l in inpf:
outf.write(l)
In python versons <= 2.6, you can use
inPipe = open("example2", "r")
outPipe = open("outputrt", "w")
for k in inPipe:
outPipe.write(k)