2

I am trying to read a file using csv.reader in python. I am new to Python and am using Python 2.7.15.

The example that I am trying to recreate is gotten from "Reading CSV Files With csv" section of this page. This is the code:

import csv

with open('employee_birthday.txt') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            print(f'Column names are {", ".join(row)}')
            line_count += 1
        else:
            print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.')
            line_count += 1
    print(f'Processed {line_count} lines.')

During execution of the code, I am getting the following errors:

File "ross_test2.py", line 11
  print(f'Column names are {", ".join(row)}')
                                         ^
SyntaxError: invalid syntax 

What am I doing wrong? How can I avoid this error. I will appreciate any help.

1 Answer 1

2

Because f in front of strings (f-strings) are only for versions above python 3.5, so try this:

print('Column names are',", ".join(row))

Or:

print('Column names are %s'%", ".join(row))

Or:

print('Column names are {}'.format(", ".join(row)))
Sign up to request clarification or add additional context in comments.

6 Comments

U9-Forward: Thanks for your help. I presume, I should also change the other print statements, perhaps.
@Ross Happy to help, :-), 😊😊😊, please accept if it works :-), and upvote :-)
U9-Forward: I really appreciate your help :-) I have accepted this answer (it will take 4 mins to show up, I guess.) I am wondering how I should change this print statement (I am getting errors in that now): " print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.') "
@Ross Try this print('\t%s works in the %s department, and was born in %s.'%row[:3])
U9-Forward: Thanks for your help (again.) I followed your suggestion. I am getting this error: "print('\t%s works in the %s department, and was born in %s.'%row)" Actually, the thing that I want to learn is how to get the characters given the row and column position in this file (using standard python libraries.)
|

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.