使用 csv 模块从 csv 文件中读取特定列?

新手上路,请多包涵

我正在尝试解析 csv 文件并仅从特定列中提取数据。

示例 csv:

 ID | Name | Address | City | State | Zip | Phone | OPEID | IPEDS |
10 | C... | 130 W.. | Mo.. | AL... | 3.. | 334.. | 01023 | 10063 |

我试图只捕获特定的列,比如 IDNameZipPhone

我看过的代码让我相信我可以通过其对应的数字来调用特定的列,所以即: 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

我希望这只会打印出我想要的每一行的特定列,除非它没有,我只得到最后一列。

原文由 frankV 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 624
2 个回答

从此代码中获取最后一列的唯一方法是,如果您的 for 循环 不包含打印语句。

这很可能是您的代码的结尾:

 for row in reader:
    content = list(row[i] for i in included_cols)
print content

你希望它是这样的:

 for row in reader:
        content = list(row[i] for i in included_cols)
        print content

现在我们已经解决了您的错误,我想借此时间向您介绍 pandas 模块。

Pandas 在处理 csv 文件方面非常出色,您只需使用以下代码即可读取 csv 并将整个列保存到变量中:

 import pandas as pd
df = pd.read_csv(csv_file)
saved_column = df.column_name #you can also use df['column_name']

因此,如果您想将列 Names 中的所有信息保存到一个变量中,您只需要做的就是:

 names = df.Names

这是一个很棒的模块,我建议您研究一下。如果由于某种原因您的打印语句在 for 循环中并且它仍然只打印出最后一列,这不应该发生,但如果我的假设是错误的,请告诉我。您发布的代码有很多缩进错误,因此很难知道应该在哪里。希望这有帮助!

原文由 Ryan Saxe 发布,翻译遵循 CC BY-SA 3.0 许可协议

import csv
from collections import defaultdict

columns = defaultdict(list) # each value in each column is appended to a list

with open('file.txt') as f:
    reader = csv.DictReader(f) # read rows into a dictionary format
    for row in reader: # read a row as {column1: value1, column2: value2,...}
        for (k,v) in row.items(): # go over each column name and value
            columns[k].append(v) # append the value into the appropriate list
                                 # based on column name k

print(columns['name'])
print(columns['phone'])
print(columns['street'])


像这样的文件

name,phone,street
Bob,0893,32 Silly
James,000,400 McHilly
Smithers,4442,23 Looped St.

会输出

>>>
['Bob', 'James', 'Smithers']
['0893', '000', '4442']
['32 Silly', '400 McHilly', '23 Looped St.']

或者,如果您想要列的数字索引:

 with open('file.txt') as f:
    reader = csv.reader(f)
    next(reader)
    for row in reader:
        for (i,v) in enumerate(row):
            columns[i].append(v)
print(columns[0])

>>>
['Bob', 'James', 'Smithers']

要更改分隔符,请将 delimiter=" " 添加到适当的实例化,即 reader = csv.reader(f,delimiter=" ")

原文由 HennyH 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题