【发布时间】:2022-01-03 00:53:28
【问题描述】:
我正在尝试创建一个以列表形式将 csv 文件读入内存的函数。当我运行我的代码时,它给了我这个错误消息(“字符串索引必须是整数”)。我是不是弄错了。 下面是代码。感谢您的帮助
# create the empty set to carry the values of the columns
Hydropower_heading = []
Solar_heading = []
Wind_heading = []
Other_heading = []
def my_task1_file(filename): # defines the function "my_task1_file"
with open(filename,'r') as myNew_file: # opens and read the file
for my_file in myNew_file.readlines(): # loops through the file
# read the values into the empty set created
Hydropower_heading.append(my_file['Hydropower'])
Solar_heading.append(my_file['Solar'])
Wind_heading.append(my_file['Wind'])
Other_heading.append(my_file['Other'])
#Hydropower_heading = int(Hydropower)
#Solar_heading = int(Solar)
#Wind_heading = int(Wind)
#Other_heading = int(Other)
my_task1_file('task1.csv') # calls the csv file into the function
# print the Heading and the column values in a row form
print('Hydropower: ', Hydropower_heading)
print('Solar: ', Solar_heading)
print('Wind: ', Wind_heading)
print('Other: ', Other_heading)
【问题讨论】:
-
readLines 会给你一个迭代,每行作为一个字符串。您正试图像字典一样使用它。查看内置的
csv库,以正确解析 csv 文件。 docs.python.org/3/library/csv.html