【发布时间】:2013-05-06 09:29:24
【问题描述】:
我正在尝试解析 csv 文件并仅从特定列中提取数据。
示例 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] 遍历每一行将产生所有第 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
我希望这只会打印出我想要的每一行的特定列,除非它没有,我只得到最后一列。
【问题讨论】:
-
为什么将
'rb'标记为open()?不应该是简单的r吗? -
@Elazar:在 Python 2(OP 正在使用)中,
"rb"适合传递给csv.reader。 -
为什么您的示例 CSV 文件将竖线字符显示为分隔符,而您的示例代码使用空格?
-
@KellyS.French 我认为这将有助于可视化数据以解决这个问题。