首页 > 解决方案 > 将 CSV 文件转换为类型化元组

问题描述

我是一个刚开始学习python的java程序员。我的第一个任务对我来说似乎很奇怪,我不知道如何处理它。我们得到一个 csv 文件,并被要求读取 csv 文件并返回代表数据的元组列表,将每个字段转换如下:

#      date: class date (see datetime module)
#      mileage: integer
#      location: string 
#      gallons: float
#      cost: float    
# Do not return a tuple for the header row.  While you can process the rawtext using string 
# functions, to receive full credit you must use Python's built in csv module. 

我真的不知道从哪里开始,尽管我想我已经知道如何读取 csv 文件。这就是我到目前为止所拥有的。

rows = []
with open(file_name) as f:
    rows=[tuple(line) for line in csv.reader(f)]
return rows

编辑:添加我的 csv 文件。 http://www.filedropper.com/mustarddata

标签: pythoncsv

解决方案


您可以遍历您生成的元组列表,根据需要转换每个值,并将其附加到新的最终列表中。或者,您可以在遍历文件行时立即执行此操作:

import csv
from datetime import datetime

data=[]

with open('mustard_data.csv') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0
    for line in csv_reader:
        # Ignore the header row
        if line_count == 0:
            line_count += 1
            continue
        else:
            # Ignore lines with missing values (or handle them otherwise if required)
            if '' not in line:  
                # Convert as appropriate
                datetime_object = datetime.strptime(line[0], '%m/%d/%Y').date()
                mileage = int(line[1])
                loc = line[2]
                gallons = float(line[3])
                cost = float(line[4].strip('$'))
                data.append((datetime_object, mileage, loc, gallons, cost))

推荐阅读