我试图解析一个CSV文件,并从特定的列中提取数据。
示例CSV:
I'm trying to parse through a csv file and extract the data from only specific columns.
Example csv:
ID | Name | Address | City | State | Zip | Phone | OPEID | IPEDS |
10 | C... | 130 W.. | Mo.. | AL... | 3.. | 334.. | 01023 | 10063 |
我想只获取特定的列,比如说ID
、Name
、Zip
以及Phone
。
我查看了相关代码后相信我可以通过对应列的编号来调用特定的列,例如:Name
对应 2
,然后通过使用 row[2]
遍历每一行就会产生第二列的所有项目。但实际上并不是这样的。
目前我已经做的:
import sys, argparse, csv
from settings import *
# command arguments
parser = argparse.ArgumentParser(description='csv to postgres',\
fromfile_prefix_chars="@" )
parser.add_argument('file', help='csv file to import', action='store')
args = parser.parse_args()
csv_file = args.file
# open csv file
with open(csv_file, 'rb') as csvfile:
# get number of columns
for line in csvfile.readlines():
array = line.split(',')
first_item = array[0]
num_columns = len(array)
csvfile.seek(0)
reader = csv.reader(csvfile, delimiter=' ')
included_cols = [1, 2, 6, 7]
for row in reader:
content = list(row[i] for i in included_cols)
print content
我期望它会按照要求输出每一行中我所需的列,但实际并没有,只输出了最后一列。
open()
函数中要使用'rb'
标志?应该不是简单的r
吗? - Elazar