0

Trying to read a csv file and print contents:

with open('C:\test.csv') as csvfile:
    csv_reader = csv.reader(csvfile, delimiter=',')
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            print(f'Column names are {", ".join(row[0])}')
            line_count += 1
        else:
            print(f'\t{row[0]} works in the {row[1]} department in {row[2]}.')

I received following error:

SyntaxError: invalid syntax
PS C:\users\XXX\documents\python> python ReadCSV.py
  File "ReadCSV.py", line 12
    print(f'Column names are {", ".join(row[0])}')
                                            ^
SyntaxError: invalid syntax
2
  • What is your Python version? What is the output of python -V or python3 -V? Commented Feb 12, 2019 at 0:07
  • Did you mean ...join(row)? Commented Feb 12, 2019 at 2:29

1 Answer 1

1

Literal String Interpolation or "f-strings" was only introduced in Python3.6.
See: https://www.python.org/dev/peps/pep-0498/

PEP498

Your code works fine on Python3.6.
If you are not using Python3.6 (and up), you will get a syntax error.

$ python3.6 -V
Python 3.6.7
$ python3.6 readcsv.py 
Column names are c, o, l, 1
        1 works in the 2 department in 3.
        4 works in the 5 department in 6.

$ python3 -V
Python 3.5.2
$ python3 readcsv.py 
  File "readcsv.py", line 9
    print(f'Column names are {", ".join(row[0])}')
                                                ^
SyntaxError: invalid syntax

$ python -V
Python 2.7.12
$ python readcsv.py 
  File "readcsv.py", line 9
    print(f'Column names are {", ".join(row[0])}')
                                                ^
SyntaxError: invalid syntax
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.