I have some code written in Python 2.7 like so :
if (os.path.exists('/path/to/my/file/somefile.txt')):
with open('/path/to/my/file/somefile.txt', 'r') as readfile:
firstline = readfile.readline()
return firstline
When I try to run this on a system that has python 2.4, I get and Invalid Syntax error:
with open('/path/to/my/file/somefile.txt', 'r') as readfile:
^
SyntaxError: invalid syntax
What am I doing wrong here?
There is no 'with' statement aka context managers in Python 2.4.
Python 2.4 is more than 10 years old.
Upgrade to Python 2.7 or 3.3.
Since with doesn't exist, could you try this instead?
import os
if (os.path.exists('/root/testing/test123.txt')):
readfile = open('/root/testing/test123.txt', 'r')
teststr = readfile.readline()
print teststr #or 'return' if you want that
Related
I am using PyCharm CE 2016.2 and python interpreter 3.5. When I tried to type the following in console, the file is generated with '123'.
>>> with open('man_data.txt', 'w') as data:
print('123', file=data)
However, when I put the same statement into a test.py file and try to run it using subprocess.call(['python', 'test.py']), it gives
>>> subprocess.call(['python', 'test.py'])
File "test.py", line 2
print('123', file=data)
^
SyntaxError: invalid syntax
1
Does anyone has any clues? Million thanks!
Python 2 is started when you call subprocess.call(['python', 'test.py']).
Try to change to subprocess.call(['python3', 'test.py']) or update the script as described here.
Here is what I try to do and I use windows and Python 3.3
LOG_FILENAME = 'log_trial_%s.txt' % datetime.datetime.now().strftime('%m%d-%H:%M:%S')
log_fd = open(LOG_FILENAME, 'w')
log_fd.write('===================\n')
The above codes are of course a part of a module and whe I ran the module, I got an error message as follows:
log_fd = open(LOG_FILENAME, 'w')
OSError: [Errno 22] Invalid argument: 'log_trial_1209-11:39:40.txt'
I have no idea what the long weird log finame means ('log_trial_%s.txt' ...) and how to fix the error thing as well.
I will appreciate your time and help.
Windows file names can't have colons in them.
Try this instead:
LOG_FILENAME = 'log_trial_%s.txt' % datetime.datetime.now().strftime('%m%d-%H%M%S')
I am trying to use "With open()" with python 2.6 and it is giving error(Syntax error) while it works fine with python 2.7.3
Am I missing something or some import to make my program work!
Any help would be appreciated.
Br
My code is here:
def compare_some_text_of_a_file(self, exportfileTransferFolder, exportfileCheckFilesFolder) :
flag = 0
error = ""
with open("check_files/"+exportfileCheckFilesFolder+".txt") as f1,open("transfer-out/"+exportfileTransferFolder) as f2:
if f1.read().strip() in f2.read():
print ""
else:
flag = 1
error = exportfileCheckFilesFolder
error = "Data of file " + error + " do not match with exported data\n"
if flag == 1:
raise AssertionError(error)
The with open() statement is supported in Python 2.6, you must have a different error.
See PEP 343 and the python File Objects documentation for the details.
Quick demo:
Python 2.6.8 (unknown, Apr 19 2012, 01:24:00)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> with open('/tmp/test/a.txt') as f:
... print f.readline()
...
foo
>>>
You are trying to use the with statement with multiple context managers though, which was only added in Python 2.7:
Changed in version 2.7: Support for multiple context expressions.
Use nested statements instead in 2.6:
with open("check_files/"+exportfileCheckFilesFolder+".txt") as f1:
with open("transfer-out/"+exportfileTransferFolder) as f2:
# f1 and f2 are now both open.
It is the "extended" with statement with multiple context expressions which causes your trouble.
In 2.6, instead of
with open(...) as f1, open(...) as f2:
do_stuff()
you should add a nesting level and write
with open(...) as f1:
with open(...) as f2:
do.stuff()
The docu says
Changed in version 2.7: Support for multiple context expressions.
The with open() syntax is supported by Python 2.6. On Python 2.4 it is not supported and gives a syntax error. If you need to support PYthon 2.4, I would suggest something like:
def readfile(filename, mode='r'):
f = open(filename, mode)
try:
for line in f:
yield f
except e:
f.close()
raise e
f.close()
for line in readfile(myfile):
print line
I keep getting the following error:
$ ./test.py
-bash: ./test.py: cannot execute binary file
when trying to run the following file in python via cygwin:
#!usr/bin/python
with open("input.txt") as inf:
try:
while True:
latin = inf.next().strip()
gloss = inf.next().strip()
trans = inf.next().strip()
process(latin, gloss, trans)
inf.next() # skip blank line
except StopIteration:
# reached end of file
pass
from itertools import chain
def chunk(s):
"""Split a string on whitespace or hyphens"""
return chain(*(c.split("-") for c in s.split()))
def process(latin, gloss, trans):
chunks = zip(chunk(latin), chunk(gloss))
How do I fix this??
After taking on the below suggestions, still getting the same error.
If this helps, I tried
$ python ./test.py
and got
$ python ./test.py
File "./test.py", line 1
SyntaxError: Non-ASCII character '\xff' in file ./test.py on line 1, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details
There is a problem. You are missing the '/' in front of usr in #!usr/bin/python. Your line should look like this.
#!/usr/bin/python
In addition to protecting the file executable, #!/usr/bin/python may not work. At least it has never worked for me on Red Hat or Ubuntu Linux. Instead, I have put this in my Python files:
#!/usr/bin/env python
I don't know how this works on Windows platforms.
I have the following code:
from lxml.builder import ElementMaker
E = ElementMaker()
params = [E.param('1'), E.param('2')]
E.p( *params, count='2')
This works fine in python 2.6, but when I run it with python 2.5, I get the following error:
E.p( *params, count='2')
^ SyntaxError: invalid syntax
I can't figure out why this is happening. Why does 2.5 throw this error? How can I fix it?
You can't follow * with keyword arguments in Python before 2.6. You can try:
E.p(*params, **{'count': '2'})
or if you'd rather:
E.p(*params, **dict(count='2')})