2014-02-26 28 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