python读取csv文件指定列的指定字段,python – 从csv文件使用csv模块读取特定列?...

我试图解析通过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

我希望这将打印出只有我想要的每一行除了它不是,我得到最后一列只有特定的列。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值