How to get data from csv into a python object

…衆ロ難τιáo~ 提交于 2021-01-18 19:14:09

问题


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

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.

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

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

I get this result:

John: score1=25.000 score2=8.333

Cheers,

Steve


回答1:


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. 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.

So if your csv file looks like that,

name,score1,score2,rank
john,85,21,1
sarah,72,19,2
bob,45,19,3

try the following code:

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.



回答2:


You can read csv file with the help of pandas.

In pandas, there is read_csv("filename/filepath") function that reads data from csv file and store it as an array.



来源:https://stackoverflow.com/questions/47128105/how-to-get-data-from-csv-into-a-python-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!