尝试将csv读入列表。
代码如下:
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
我的输出是:
[['one','two','three']]
Traceback():
....
line 11, in gen_list
reader = csv.reader(fin)
AttributeError: 'str' object has no attribute 'reader'
我可以通过将“ import csv”作为gen_list函数的第一行来防止发生此错误。
为什么将代码放在函数中不起作用?
答案 0 :(得分:0)
结果是我偶然在另一个函数中使用了csv。一旦我更改了csv,问题就消失了
功能:
def get_list(csv):
with open(csv,'rt') as fin:
for line in fin:
drList.append(gen_list(line))
return (drList)
答案 1 :(得分:-1)
尝试一下:
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
reader
中open
中gen_list
的缩进似乎是错误的