python-3.x - 如何从csv获取数据到python对象中

标签 python-3.x object import-csv

我是一个初学者python用户。无法以所需的对象格式将数据从 csv 获取到 python 以满足 python 函数。
如果我在 python 中手动创建数据(而不是从 csv 中引入),则以下代码有效:

class Student(object):
   pass

john = Student()
#score tuple
john.score = (85.0, 42.0/2.0)

bob = Student()
bob.score = (45.0, 19.0/2.0)

john.rank = 1
bob.rank = 2

ExternalCode.AdjustStudents([john, bob])

但是,我需要它自动工作,而不必每次都手动输入数据,因为会有数千个更新 - 因此需要能够从 csv 中引入数据。

.csv 文件格式为:
约翰, 85, 21, 1
鲍勃, 45, 9.5, 2

Student 对象将具有分数属性(第 2 列和第 3 列作为元组)以及排名属性(第 4 列)。所需的对象格式与上面手动代码生成的格式相同。

手动代码生成的所需格式的一个示例是,当我在手动代码之后执行以下打印时:
print(" John: score1={0[0]:.3f} score2={0[1]:.3f}".format(john.skill)) 

我得到这个结果:

约翰: score1=25.000 score2=8.333

干杯,

史蒂夫

最佳答案

如果我理解正确,你是在问如何才能create variables dynamically .操纵globals() dict 创建新变量不是一个好主意,您应该使用列表或字典来存储您的 csv 数据。

你似乎需要一个列表,所以:

  • 定义列表(下例中的 student_list)。
  • 打开 .csv 文件。
  • 创建一个 csv.reader .
  • 遍历行。
  • 将数字转换为浮点数。
  • 创建一个 Student实例并传递名称和数字。
  • 最后将此学生实例附加到 student_list .

  • 所以如果你的 csv 文件看起来像这样,
    name,score1,score2,rank
    john,85,21,1
    sarah,72,19,2
    bob,45,19,3
    

    试试下面的代码:
    import csv
    
    
    class Student:
    
        def __init__(self, name, score, rank):
            self.name = name
            self.score = score
            self.rank = rank
    
    
    student_list = []
    
    with open('temp.csv', newline='') as csv_file:
        reader = csv.reader(csv_file)
        next(reader, None)  # Skip the header.
        # Unpack the row directly in the head of the for loop.
        for name, score1, score2, rank in reader:
            # Convert the numbers to floats.
            score1 = float(score1)
            score2 = float(score2)
            rank = float(rank)
            # Now create the Student instance and append it to the list.
            student_list.append(Student(name, (score1, score2), rank))
    
    # Then do something with the student_list.
    

    关于python-3.x - 如何从csv获取数据到python对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47128105/

    相关文章:

    sql-server - 将包含超过 1024 列的 csv 文件导入到新的 SQL Server 表中

    python - 为什么 NotImplemented 在 Python 3 中是真实的?

    python - 如何从 Python 元组或列表中提取字符串?

    python-3.x - Python 3+ Tkinter 中心标签文本

    设置对象属性时出现 C++ 内存访问冲突

    python - 将字符串转换为 float 以求和时忽略所有非浮点值

    python - 执行器上的 Spark 2.3 内存泄漏

    javascript - 将数组中的对象移动到末尾

    php - 通过引用方法传递对象数组

    powershell - 在Powershell中从CSV导入数据提供的英国CSV日期少于7天