python - 将 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
解决方案
您可以遍历您生成的元组列表,根据需要转换每个值,并将其附加到新的最终列表中。或者,您可以在遍历文件行时立即执行此操作:
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))
推荐阅读
- python - 为什么它不能正确执行 python 脚本?Laravel Symfony
- awk - 搜索图案并打印计数
- c# - Xamarin 表单 - Instagram 登录:出现 Invalid redirect_uri 错误,如何解决?
- snowflake-cloud-data-platform - Snowflake 中允许的子查询
- objective-c - NSTextView 中的 MouseMoved 通知产生消息“共享项数组为空”
- python - 在 Django REST 框架中分组、注释和显示来自父模型的额外数据
- postgresql - 使用 Postgres UUID 类型的 JPA Criteria API 问题
- google-apps-script - 调试 GAS Web App doPost 以查看执行错误的输出
- python - 如何从CSV文件中提取xml数据
- javascript - 如何在带有接口的打字稿中声明函数参数?