简体   繁体   中英

Python function can't see an imported module

Trying to read a csv into a list.

Code is as follows:

import csv

with open('file.csv','r') as fin:
    reader = csv.reader(fin)
    mylist = list(reader)

print (mylist)

def gen_list():
    with open('file.csv','r') as fin:
        reader = csv.reader(fin)
        mylist = list(reader)
    print (mylist)

def main():
    gen_list()
    return 0

My output is:

[['one','two','three']]

Traceback():
....
line 11, in gen_list
reader = csv.reader(fin)
AttributeError: 'str' object has no attribute 'reader'

I can prevent this error occurring by putting 'import csv' as the first line of the gen_list function.

why does the code not work when placed in a function?

Turns out I was using csv in another function by accident. Once I changed csv the issue went away

Function:

def get_list(csv):
    with open(csv,'rt') as fin:
        for line in fin:
            drList.append(gen_list(line))
        return (drList)

Try this:

import csv

with open('file.csv','r') as fin:
    reader = csv.reader(fin)
    mylist = list(reader)

print (mylist)

def gen_list():
    with open('file.csv','r') as fin:
        reader = csv.reader(fin)
        mylist = list(reader)
    print (mylist)

def main():
    gen_list()
    return 0

It seems that the indentation for reader within the open within gen_list is wrong

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM