阅读csv文件python的问题

时间:2016-11-24 17:29:48

标签: python csv

我试图读取csv文件,但出于某种原因,当我要求它打印时,它会打印内存地址而不是表格。

以下是我的结果:

>>> read_table('books.csv')

['books.csv', 'boxoffice.csv', 'imdb.csv', 'olympics-locations.csv', 'olympics-results.csv', 'oscar-actor.csv', 'oscar-film.csv', 'seinfeld-episodes.csv', 'seinfeld-foods.csv']

<_csv.reader object at 0x03977C30>

这是我的代码:

import csv

import glob
from database import *

def read_table(name):
    '''
    (str) -> Table
    Given a file name as a string, the function will return the file as a Table
    object.
    '''
    # create a list that stores all comma-separate files(*.csv)
    files_list = glob.glob('*.csv')
    print(files_list)
    # check if the desired file is in the list
    if(name in files_list):
        # if found, open the file for reading
        with open(name) as csvfile:
            readCSV = csv.reader(csvfile, delimiter = ',')
            print(readCSV)

我的剧本中有些东西是假的吗?

2 个答案:

答案 0 :(得分:2)

试试这个:

for line in readCSV:
    print(line)

有关更完整的示例和说明,请参阅docs。简而言之,csvreader返回一个迭代器对象(列表也是一个迭代器)。

答案 1 :(得分:0)

import csv
from collections import defaultdict

col_names = defaultdict(list)

with open(filename) as f:
    reader = csv.DictReader(f) 
    for each_row in reader: 
        for (i,j) in each_row.items(): 
            col_names[i].append(j) 


print(col_names[column name])