我试图解析通过csv文件,并从只提取特定列的数据。
示例csv:
ID | Name | Address | City | State | Zip | Phone | OPEID | IPEDS |
10 | C... | 130 W.. | Mo.. | AL... | 3.. | 334.. | 01023 | 10063 |
我试图只捕获特定的列,说ID,名称,Zip和电话。
我看过的代码使我相信我可以通过其相应的数字调用特定的列,因此:名称将对应于2和迭代通过每行使用行[2]将产生列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
我希望这将打印出只有我想要的每一行除了它不是,我得到最后一列只有特定的列。