读取csv文件时出现问题

2024-04-26 12:35:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图读取一个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)

我的剧本有错吗?你知道吗


Tags: csvthenameimportreadifastable
2条回答

试试这个:

for line in readCSV:
    print(line)

有关更完整的示例和说明,请参见docs。简单地说,csvreader返回一个迭代器对象(列表也是迭代器)。你知道吗

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])

相关问题 更多 >