0

Please advise how I'm getting the following error:

File "/Users/<username>/PycharmProjects/OOP/csv_write.py", line 8
  print(f'Column names are {", ".join(row)}')
                                           ^
SyntaxError: invalid syntax

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.')

As I'm trying to read from the file and display the information as follows as per the link.

employee_birthday.txt :

name,department,birthday month
John Smith,Accounting,November
Erica Meyers,IT,March

This question has been resolved and thank you for the responses below.

Eugene_S
  • 110
  • 1
  • 1
  • 10
  • show and example for the data – Denis Tsoi May 28 '20 at 16:06
  • 2
    Please update your question with the full text of your code and full error traceback. – quamrana May 28 '20 at 16:08
  • Thanks, this is the code and sample data checked into the Git repository and it worked as suggested by @FishingCode: https://github.com/eugenesheyko/csv_write/blob/master/csv_write.py#L13 Appreciate if you can also advise how to print the 'line_count' variable and the names of the columns. – Eugene_S May 28 '20 at 17:07

2 Answers2

1

Try this for that line the traceback is referring to:

f-strings apply for py3.5 and greater versions, see if either of these work:

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

OR

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

OR

print('Column names are {}'.format(", ".join(row)))
de_classified
  • 1,927
  • 1
  • 15
  • 19
  • Thanks, I've managed to update the print statements as follows: https://github.com/eugenesheyko/csv_write/blob/master/csv_write.py – Eugene_S May 28 '20 at 18:47
  • 1
    "*f-strings apply for py3.5*" It was [introduced in Python 3.6](https://www.python.org/dev/peps/pep-0498/), not 3.5. – Gino Mempin May 28 '20 at 23:46
1

Make sure you are using Python >= 3.6 as f-strings were introduced later. If that still doesn't work, check the indentation for the code.

MIB
  • 46
  • 3