如何从csv获取数据到python对象中 [英] How to get data from csv into a python object

查看:97
本文介绍了如何从csv获取数据到python对象中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am a beginner python user. Having trouble getting data from csv into python in the required object format to satisfy a python function. If I manually created the data in python (rather than bringing it in from csv) the following code works:

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 中导入数据.

However I need it to work automatically and not have to manually type out the data each time as there are going to be thousands of updates - hence the need to be able to bring in the data from csv.

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

The csv file format is: john, 85, 21, 1 bob, 45, 9.5, 2

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

Student objects would have a score attribute (columns 2 and 3 as a tuple) as well as a rank attribute (column 4). The required object format would be the same as produced by the manual code above.

手动代码生成的所需格式的一个例子,是当我在手动代码之后执行以下打印时:

An example of the required format produced by the manual code, is that when I do the following print after the manual code:

print(" John: score1={0[0]:.3f} score2={0[1]:.3f}".format(john.skill)) 

我得到这个结果:

约翰:score1=25.000 score2=8.333

John: score1=25.000 score2=8.333

干杯,

史蒂夫

推荐答案

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

If I understand you correctly, you're asking how you can create variables dynamically. Manipulating the globals() dict to create new variables is not a good idea and you should rather use a list or dictionary to store your csv data.

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

You seem to need a list, so:

  1. 定义列表(下例中的student_list).
  2. 打开 csv 文件.
  3. 创建一个csv.reader.
  4. 遍历行.
  5. 将数字转换为浮点数.
  6. 创建一个 Student 实例并传递姓名和编号.
  7. 最后将此学生实例附加到student_list.
  1. Define the list (student_list in the example below).
  2. Open the csv file.
  3. Create a csv.reader.
  4. Iterate over the rows.
  5. Convert the numbers to floats.
  6. Create a Student instance and pass the name and numbers.
  7. Finally append this student instance to the student_list.

所以如果你的 csv 文件看起来像这样,

So if your csv file looks like that,

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.

这篇关于如何从csv获取数据到python对象中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆