【问题标题】:A function to read CSV data from a file into memory将文件中的 CSV 数据读入内存的函数
【发布时间】: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

标签: python csv


【解决方案1】:

我们可以使用csv.DictReader method按列读取CSV文件。

代码:(code.py)

import csv


def my_task1_file(filename):  # defines the function "my_task1_file"
    Hydropower_heading = []
    Solar_heading = []
    Wind_heading = []
    Other_heading = []
    with open(filename, newline='\n') as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            # read the values into the empty set created
            Hydropower_heading.append(row['Hydropower'])
            Solar_heading.append(row['Solar'])
            Wind_heading.append(row['Wind'])
            Other_heading.append(row['Other'])
    return Hydropower_heading, Solar_heading, Wind_heading, Other_heading

if __name__ == "__main__":
    Hydropower_heading, Solar_heading, Wind_heading, Other_heading = my_task1_file('task1.csv')

    # 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)

task1.csv:

Hydropower,Solar,Wind,Other
5,6,3,8
6,8,5,12
3,6,9,7

输出:

Hydropower:  ['5', '6', '3']
Solar:  ['6', '8', '6']
Wind:  ['3', '5', '9']
Other:  ['8', '12', '7']

说明:

  • __main__ 条件将检查文件是否直接运行。如果使用python code.py 直接运行文件,它将执行该部分。否则如果我们从另一个python文件中导入code.py,这部分将不会被执行。
  • 您可以根据需要删除__main__ 块,如下所示。但是,在使用__main__ 块从另一个python 文件导入一个python 文件时,将方法与执行分开是一个很好的做法。让我知道它是否能消除您的困惑。

code.py(没有__main__):

import csv


def my_task1_file(filename):  # defines the function "my_task1_file"
    Hydropower_heading = []
    Solar_heading = []
    Wind_heading = []
    Other_heading = []
    with open(filename, newline='\n') as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            # read the values into the empty set created
            Hydropower_heading.append(row['Hydropower'])
            Solar_heading.append(row['Solar'])
            Wind_heading.append(row['Wind'])
            Other_heading.append(row['Other'])
    return Hydropower_heading, Solar_heading, Wind_heading, Other_heading

Hydropower_heading, Solar_heading, Wind_heading, Other_heading = my_task1_file('task1.csv')

print('Hydropower: ', Hydropower_heading)
print('Solar: ', Solar_heading)
print('Wind: ', Wind_heading)
print('Other: ', Other_heading)

参考资料:

【讨论】:

  • if name == "main": 什么会取代这条评论,因为我在这里有点困惑,拜托
  • 我浏览了文档。我不应该使用任何 python 模块来编写我的代码。因此,无论如何我可以让它运行,因为我仍然收到一条错误消息。谢谢
  • 嗨@EugeneGyimah!我已经更新了解释 __main__ 块的答案。让我知道它是否能消除您的困惑。
  • 抱歉,您的代码包含导入 csv,这不是我工作的要求。有没有办法绕过它?您的代码运行良好,但我不想使用任何 python 模块。谢谢
【解决方案2】:

由于错误是“字符串索引必须是整数”,因此您必须使用不能将字符串值作为索引的数据类型。在这段代码中...

for my_file in myNew_file.readlines():
     
     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”、“Solar”、“Wind”和“Other”作为索引值,它们不能是 my_file 的有效索引值,我假设它是字符串数据类型,因为您正在读取文件myNew_file。如果您将这些值更改为适当的整数,则该错误将不再出现。

【讨论】:

  • 请问是怎么做的?
  • 假设你的csv的每一行有四个值,用逗号分隔,格式为num0,num1,num2,num3,如果你想让第一列对应“Hydropower”,第二列对应“Solar”,等等,那么你可能会这样做:用my_file[0]替换my_file['Hydropower'];将my_file['Solar'] 替换为my_file[1];将my_file['Wind'] 替换为my_file[2];并将my_file['Other'] 替换为my_file[3]。让我知道这是否有效。
  • 它只显示列的前几位。例如,如果值为 2.305,则返回 2,然后是下一个值
  • csv 列中的每个值都应该是整数还是浮点数?似乎问题在于您有一个浮点数,其类型已更改为整数。例如,int(2.305) 将评估为 2,正如您所解释的,依此类推。
猜你喜欢
  • 1970-01-01
  • 2014-02-15
  • 2013-05-17
  • 1970-01-01
  • 1970-01-01
  • 2018-07-10
  • 2020-05-02
  • 2011-05-16
  • 1970-01-01
相关资源
最近更新 更多