Python:查找CSV文件中的列位置

Python:查找CSV文件中的列位置,python,csv,Python,Csv,我有一个包含以下信息的csv文件: team;name;city;country;points VCF;Valencia;Valencia;Spain;98 FCB;Barcelona;Barcelona;Spain;54 MU;Manchester;Manchester;England;87 我想知道如何返回显示“城市”信息的列号,并将其保存在变量“X”中。在上面的示例中,它将是“2”,因为它出现在第三个位置 这是我目前掌握的代码: import csv file = 'spanishle

我有一个包含以下信息的csv文件:

team;name;city;country;points
VCF;Valencia;Valencia;Spain;98
FCB;Barcelona;Barcelona;Spain;54
MU;Manchester;Manchester;England;87
我想知道如何返回显示“城市”信息的列号,并将其保存在变量“X”中。在上面的示例中,它将是“2”,因为它出现在第三个位置

这是我目前掌握的代码:

import csv

file = 'spanishleague2012'
csv_file = csv.reader(open(file))
next(csv_file)

x = [column== city]

print x

结果应该是:2

您只需打开文件进行读取并检查第一个标题:

f = [i.strip('\n').split(";") for i in open('filename.csv')]
print(f[0].index("city"))
您可以在标题行上使用,检查列名:

import csv

with open(filename) as f:
    reader = csv.reader(f, delimiter=";")        
    for idx, col in enumerate(next(reader)):
        if col == "city":
            print idx
            break
如果目标是访问所有城市值,则可以使用:


与其跳过标题,不如读入它。然后查找名为
“city”
的列的索引:

在这种情况下,您将拥有数组
col
中所有列的列表

 print cols 
>>>['team', 'name', 'city', 'country' , 'points']
现在,您可以将城市列的索引设置为

X = cols.index("city")

这将读取您的文件并返回
2

import csv

with open('spanishleague2012','rb') as f:
    csv_file = csv.reader(f,delimiter=';')
    header = next(csv_file)
    print header.index('city')
但使用DictReader,您不需要知道列号:

import csv

with open('spanishleague2012','rb') as f:
    csv_file = csv.DictReader(f,delimiter=';')
    for row in csv_file:
        print row['city']
输出:

Valencia
Barcelona
Manchester

使用
csv.DictReader()
,您会轻松得多;那么每一行都有一个
'city'
键。@Martijn查找“city”列的位置有什么帮助?您不需要这样做。最终目标是访问所有城市的价值观。这似乎太特别了。CSV文件中的列除了分隔符外,还可以包含“
”;“
s。
import csv

with open('spanishleague2012','rb') as f:
    csv_file = csv.reader(f,delimiter=';')
    header = next(csv_file)
    print header.index('city')
import csv

with open('spanishleague2012','rb') as f:
    csv_file = csv.DictReader(f,delimiter=';')
    for row in csv_file:
        print row['city']
Valencia
Barcelona
Manchester