【问题标题】:retrieve the contents of the csv file as the lists检索 csv 文件的内容作为列表
【发布时间】:2013-11-10 14:52:52
【问题描述】:

将 csv 文件的内容作为列表检索的最佳和最优雅的方法是什么?请注意,国家、地区和人口等必填列将在下面的程序中自动识别。

with open ('data.csv','r') as infile:
    contents = infile.read().split(',')

with open ('data.csv','r') as infile:
    countries = [item.split(',')[contents.index('Country')] for item in infile]

with open ('data.csv','r') as infile:
    areas = [item.split(',')[contents.index('Area')] for item in infile]

with open ('data.csv','r') as infile:
    populations = [item.split(',')[contents.index('Population')] for item in infile]

print (countries)
print (areas)
print (populations)

上述程序有效,但正在寻找非常简短易读的程序。

更新: 为了防止在某些文件中不存在某些列(例如“国家”)时出现错误,可以通过以下方式改进程序:

countries = [item.split(',')[contents.index('Country')] for item in infile if 'Country' in contents]

如何使用 csv 模块完成?

【问题讨论】:

标签: python csv python-3.x


【解决方案1】:

对 CSV 文件使用 csv module

import csv

countries = []
areas = []
populations = []

with open ('data.csv', newline='') as infile:
    reader = csv.DictReader(infile)
    for row in reader:
        countries.append(row['Country'])
        areas.append(row['Area'])
        populations.append(row['Population'])

DictReader() 类自动使用第一行标题作为文件其余部分的键。

或使用:

import csv

with open ('data.csv', newline='') as infile:
    reader = csv.reader(infile)
    next(reader, None)  # skip the header first
    countries, areas, populations = zip(*reader)

如果你只有 3 列,国家、地区和人口,按顺序排列。

【讨论】:

  • 谢谢。我更喜欢使用 DictReader 的第一种方法,因为这些列是未知的。但是,当批处理过程中某些文件中不存在指定的列标题(例如“区域”)时,如何避免键错误? @Martijn Pieters
  • 测试密钥:if 'Area' in row:
猜你喜欢
  • 1970-01-01
  • 2018-04-22
  • 2019-05-04
  • 1970-01-01
  • 2020-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多