检索csv文件内容作为列表的最佳和最优雅的方法是什么?请注意,所需的列(如Country,Area和Population)将自动标识,如下面的程序所示。
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模块完成?
答案 0 :(得分:3)
将csv
module用于CSV文件:
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列,国家,地区和人口,则按此顺序。