错误消息:
File "./reading_and_creating_outage_report.py", line 6
with open('major_outages_csv.csv',mode='w') as csv_file:
^
SyntaxError: invalid syntax
我很难过。我在Stack Overflow和其他地方看到的每个例子都使用这种语法来打开一个与脚本位于同一个directroy中的csv文件。我找到了其他方法,但我不喜欢不知道我写这个的方式有什么问题,因为它似乎与所有其他样本相同。
参考资料:
https://realpython.com/python-csv/
https://docs.python.org/2/library/csv.html
有问题的脚本:
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.')
更新:问题是python的版本。正如StackExchange上的许多其他帖子中所提到的,早于2.5的python版本不支持with
语句。
如果希望使用早于2.5的python版本读取.csv文件,则以下脚本可以正常工作。
import csv
csv_reader = csv.reader(open("file_name.csv","rb"),delimiter=',')
for fields in csv_reader:
print fields