1

The error message:

File "./reading_and_creating_outage_report.py", line 6
with open('major_outages_csv.csv',mode='w') as csv_file:
         ^
SyntaxError: invalid syntax

I'm stumped. Every example I've seen on Stack Overflow and elsewhere uses this syntax to open a csv file residing in the same directroy as the script. I have found other methods, but I don't like not knowing what is wrong with the way I'm writing this considering it seems to be the same all other samples.

referenced material:

https://realpython.com/python-csv/

https://docs.python.org/2/library/csv.html

script in question:

import csv
with open('major_outages_csv.csv',mode='w') as csv_file:
    csv_reader  = csv.reader(csv_file,delimiter=',')
    line_count = 0
    for row in csv_reader:
            if line_count == 0:
                    print('column headers are {", ".join(row)}')
                    line_count += 1
            else:
                    print('\t{row[0]} is the number of customers out and {row[1]} is the feeder.')
                    line_count += 1
    print ('processed {line_count} lines.')
6
  • Your indentation is out in places. That will produce errors. Keep indentations to 4 spaces only Commented Feb 19, 2019 at 15:18
  • Please make sure to include the complete code. Your traceback mentions line 6, but in your sample it would be line 2 Commented Feb 19, 2019 at 15:18
  • 1
    I tried the code you posted and there is no SyntaxError. My only suggestion is that you are using very old version of Python below 2.5 that doesn't support with statement Commented Feb 19, 2019 at 15:19
  • it's true. I excluded commented lines. Commented Feb 19, 2019 at 15:20
  • 1
    The version must be the problem. My version is 2.4.3 (it cannot be updated). I think this thread may provide the solution: stackoverflow.com/questions/18651456/… Commented Feb 19, 2019 at 15:26

1 Answer 1

1

UPDATE: The issue was the version of python. As mentioned in many other posts on StackExchange, python versions older than 2.5 do not support with statements.

If one wishes to read a .csv file using a version of python older than 2.5, the below script works.

import csv
csv_reader = csv.reader(open("file_name.csv","rb"),delimiter=',')
for fields in csv_reader:
     print fields
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.