简体   繁体   English

将CSV文件导入Python

[英]import CSV file to Python

I am trying to import csv file to Python. 我正在尝试将csv文件导入Python。 I have two question here. 我这里有两个问题。

Q1. Q1。 my code is: 我的代码是:

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

But there is an error message here 但是这里有一条错误信息

IndexError: list index out of range IndexError:列表索引超出范围

Q2. Q2。 my data output looks like 我的数据输出看起来像

['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', '', '']
.....
....

Do I have to use 'r' or 'rb' function in reading the file ? 在阅读文件时是否必须使用'r'或'rb'功能?

I want to see the 2nd and the 8th row of the CSV file. 我想看看CSV文件的第2行和第8行。

your row has 6 elements and you're trying to print the 2nd and the 9th. 你的行有6个元素,你正在尝试打印第2和第9个。 well, the latter does not exist, hence list index out of range (indexing starts with 0). 好吧,后者不存在,因此列表索引超出范围(索引从0开始)。

If you just want rows 2-8, use itertools.islice on the reader object: 如果您只想要第2-8行,请在reader对象上使用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)

If you just want those two specific rows use a step of 6: 如果您只想要这两个特定行,请使用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)

Or call next on the reader object after skipping the first line: 或者在跳过第一行后在reader对象上调用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)

Or using enumerate: 或者使用枚举:

 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM