2014-02-26 30 views
0

我遇到了问题。在Python中打印csv文件的字段位置

我有一个csv文件,我应该看看5个第一行。第1-4行包含元数据。第1行是css文件的字段列表。 的queastion是

打印字段的位置,例如:

0 URI

1 RDF-模式#标签

2 RDF-模式#评论

3 basedOn_label

4 basedOn

5预算

怎么做呢

+0

请把到目前为止你已经尝试了代码。 –

+1

欢迎来到StackOverflow,请阅读 http://stackoverflow.com/questions/how-to-ask来帮助我们帮助你。 –

回答

0

也许enumerate可以帮助你:

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter'] 
>>> list(enumerate(seasons)) 
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')] 
>>> list(enumerate(seasons, start=1)) 
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')] 
0

生成一个例子CSV:

$ cat <<EOF> the.csv 
> URI, basedOn, budget 
> 1, 2, 3 
> 4, 5, 6 
> EOF 

Python代码做你想做的

fh = open('the.csv', 'r') 
line = fh.readline().strip().split(',') 
for pos, field in enumerate(line): 
    print pos, field 

# ... continue reading the rest of `fh` 

输出我的控制台上:

0 URI 
1 basedOn 
2 budget