0

There are several questions on SO that seem to deal with my problem. However, they all seem to be caused by using a pre-2.6 version of Python. Which is not the case here. I appreciate any help tracking down the cause of this.

I get a Syntax Error when I try to use a with open() as f construct.

Here's the code (test.py):

#!/usr/bin/env python

import sys
print sys.version

fname = "/tmp/test.txt"

open(fname, 'a').close()

with open(fname, 'a') as fh
  fh.write("test")

Here's the output:

$ ./test.py
  File "./test.py", line 10
    with open(fname, 'a') as fh
                              ^
SyntaxError: invalid syntax

Python version being used:

$ /usr/bin/env python
Python 2.7.10 (default, Oct 14 2015, 16:09:02)
[GCC 5.2.1 20151010] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>

$ whereis python
python: /usr/bin/python3.4 /usr/bin/python /usr/bin/python3.4m /usr/bin/python3.3 /usr/bin/python3.3m /usr/bin/python2.7 /usr/lib/python3.4 /usr/lib/python3.3 /usr/lib/python3.5 /usr/lib/python2.7 /etc/python3.4 /etc/python /etc/python3.3 /etc/python2.7 /usr/local/lib/python3.4 /usr/local/lib/python3.3 /usr/local/lib/python2.7 /usr/include/python2.7 /usr/share/python /usr/share/man/man1/python.1.gz

My system info:

$ uname -a
Linux ... 4.2.0-27-generic #32-Ubuntu SMP Fri Jan 22 04:49:08 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux

Thanks!

2
  • 4
    Put ':' as with open(fname, 'a') as fh: and You should delete this question Commented Feb 6, 2016 at 15:47
  • open(name, 'a').close() can be removed. You don't gain anything by opening (or attempting to open) and immediately closing the file. Commented Feb 6, 2016 at 17:07

1 Answer 1

3

You need a : after your with statement

with open(fname, 'a') as fh:
  fh.write("test")
Sign up to request clarification or add additional context in comments.

2 Comments

How utterly stupid of me! Thanks for pointing that out. You made my day.
You wouldn't believe how long I've been staring at this, haha. LOL!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.