1

I'm trying to read a csv file but for some reason when I ask it to print, it prints the memory address instead of the table.

Below is my result :

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

This is my code :

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)

Something is false in my script ?

1
  • According to the documentation, csv.reader returns a reader object which will iterate over lines in the given csvfile. So in order to print the file, you should iterate over the object, for each iteration the object will return a new line of data. This line can then be printed if that is desired. Commented Nov 24, 2016 at 17:37

2 Answers 2

2

Try this:

for line in readCSV:
    print(line)

See docs for a more complete example and explanation. Briefly csvreader returns an iterator object (a list is also an iterator).

Sign up to request clarification or add additional context in comments.

2 Comments

Oh it worked this time. Do you know the reason why this happens?
@ShamanthChedde - you created a reader but didn't read from it. The example and referenced documentation show one way to do it. You could also do table = list(readCSV).
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])

2 Comments

Please, could you explain what you try to do with your code.
It will print all the data under your given column name

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.