3

i have a syntax error with the with statement. i cant figure it out. i am using python 3 and every time i use the with statement it just wont have it. i am trying to make a reader for a txt file and i need this with statement.

import csv

value1 = "Spam"

fname = input(open("Please enter the name of the file you wish to open: ")

with open(fname, 'rb') as csvfile:
    spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
    for row in spamreader:
        if value1 in row:
            print(" ".join(row)) 

i am very new to python its probably very obvious cheers for the help guys

1
  • 1
    Aside: if you're opening a csv file in Python 3, you should use open(fname, 'r', newline='') instead of open(fname, 'rb') (which is how you did it in Python 2.) See the docs. Commented Dec 8, 2013 at 16:30

1 Answer 1

4

The syntax error is not caused by with, but print statement. In Python 3.x, print is a function.

>>> print 1
  File "<stdin>", line 1
    print 1
          ^
SyntaxError: invalid syntax
>>> print(1)
1
>>>

So the following line:

print " ".join(row) 

should be replaced with:

print(" ".join(row))

In the following sentence, a parenthesis is missing.

fname = input(open("Please enter the name of the file you wish to open: "))
#                                                                         ^

And open should be omitted:

fname = input("Please enter the name of the file you wish to open: ")
Sign up to request clarification or add additional context in comments.

1 Comment

@user3077551: please edit the entire traceback into your question. Possibly you have an unclosed parenthesis on an earlier line.

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.