我正在嘗試解析 csv 文件並僅從特定列中提取數據。
示例 csv:
<代碼>ID | 名稱 | 地址 | 城市 | 州 | 郵編 | 電話 | 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文件", action ="store") args = parser.parse_args() csv_file = args.file # open(csv_file, "rb") as csvfile: # 獲取 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閱讀器中的行: content = list(row[i] for i in included_cols) print content
我希望這只會打印出我想要的每一行的特定列,除了它沒有,我只得到最後一列。