0

I have the following file:

import sys

lines = []
with open(sys.argv[1]) as f: #this works fine
    for line in f:
        lines.append(line.replace('\\', '/')
with open(sys.argv[1], 'w') as f: #this gives a syntax error
    for line in lines:
        f.write(line)   

Whenever I try to run it, I get a syntax error on the with part of the second with statement:

  File "ChangeSlashes.py", line 7
    with open(sys.argv[1], 'w') as f:
       ^
SyntaxError: invalid syntax

Why is this happening, and why is it only when I specify the mode in open()?

3
  • 3
    lines.append(line.replace('\\', '/') didnt close parens on previous line. Commented Oct 30, 2016 at 23:54
  • @PaulRooney Of course. And here I was thinking it's some obscure version difference thing or something. Commented Oct 30, 2016 at 23:57
  • Its a shame it can't point to the line with the problem. I get this issue all the time particularly with IDE's that swallow parens. You just learn to look for it after a while though. Commented Oct 31, 2016 at 0:00

1 Answer 1

2

Replace

lines.append(line.replace('\\', '/')

with:

lines.append(line.replace('\\', '/'))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.