将CSV文件导入Python

时间:2015-04-17 09:59:27

标签: python csv

我正在尝试将csv文件导入Python。我在这里有两个问题。

Q1。我的代码是:

import csv
with open('highfrequency2.csv') as csvfile:
  freq=csv.reader(csvfile, delimiter=',')
  for row in freq:
    print(row[1],row[8])

但是这里有一条错误信息

IndexError:列表索引超出范围

Q2。我的数据输出看起来像

['WOSl.TQ', '02-Jan-14', '51:48.0', 'Quote', '', '']
['WOSl.TQ', '02-Jan-14', '51:48.0', 'Quote', '', '']
['WOSl.TQ', '02-Jan-14', '51:48.0', 'Quote', '', '']
['WOSl.TQ', '02-Jan-14', '51:48.0', 'Quote', '', ''] 
['WOSl.TQ', '02-Jan-14', '51:48.0', 'Quote', '', '']
.....
....

我必须使用' r'或者' rb'读取文件的功能?

我想查看CSV文件的第2行和第8行。

2 个答案:

答案 0 :(得分:2)

你的行有6个元素,你正在尝试打印第2和第9个。好吧,后者不存在,因此列表索引超出范围(索引从0开始)。

答案 1 :(得分:1)

如果您只想要第2-8行,请在阅读器对象上使用itertools.islice

import csv
from itertools import islice, izip

with open('highfrequency2.csv') as csvfile:
    freq = csv.reader(csvfile)
    # create islice object
    interest = islice(freq, 1, 8, None))
    # iterate over islice object getting row at a time
    for row in interest:
       print(row)

如果您只想要这两个特定行,请使用step 6:

 import csv
from itertools import islice, izip

with open('highfrequency2.csv') as csvfile:
    freq = csv.reader(csvfile)
    interest = islice(freq, 1, 8, 6))
    for row in interest:
       print(row)

或者在跳过第一行后在读者对象上调用next:

import csv

with open('highfrequency2.csv') as csvfile:
    freq = csv.reader(csvfile)
    next(freq)
    # create generator expression
    interest = (next(freq) for _ in range(7))
    for row in interest:
       print(row)

或使用枚举:

 import csv

with open('highfrequency2.csv') as csvfile:
    freq = csv.reader(csvfile)
    interest = (row for ind, row in enumerate(freq) if ind in {1,7})
    for row in interest:
       print(row)