[英]Invalid syntax when opening .csv file in python
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.我在 Stack Overflow 和其他地方看到的每个示例都使用此语法打开与脚本位于同一目录中的 csv 文件。 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://realpython.com/python-csv/
https://docs.python.org/2/library/csv.html 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.')
UPDATE: The issue was the version of python.更新:问题是python的版本。 As mentioned in many other posts on StackExchange, python versions older than 2.5 do not support with
statements.正如 StackExchange 上的许多其他帖子所述,2.5 之前的 Python 版本不支持with
语句。
If one wishes to read a .csv file using a version of python older than 2.5, the below script works.如果希望使用早于 2.5 的 python 版本读取 .csv 文件,则以下脚本有效。
import csv
csv_reader = csv.reader(open("file_name.csv","rb"),delimiter=',')
for fields in csv_reader:
print fields
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.