当我从脚本访问csv.reader
时,每件事都运行良好但是当我从类中的方法访问它时,我收到以下错误:
AttributeError: 'GetInstgramUsernames' object has no attribute 'reader'
我看过这两个类似的问题我的问题不同
基于这两个链接,我确保了
我是Python新手,所以它可能只是一个简单的疏忽,但我已经包含了代码和注释,哪些有效,哪些无效
import csv
print(csv.__file__)
# displays:
# D:\ProgramData\Anaconda2\lib\csv.pyc
reader = csv.reader(open('D:\\dev\\scrapy\\instagram_influencers\\instagram_influencers\\input\\user_names.csv','r'))
print(list(reader))
# displays
# [['user_name'], ['mensfashionpost'], ['creativefasion']]
class GetInstgramUsernames(object):
def read(self):
# same line as above but produces an error
# AttributeError: 'GetInstgramUsernames' object has no attribute 'reader'
self.xyz = csv.reader(open('D:\\dev\\scrapy\\instagram_influencers\\instagram_influencers\\input\\user_names.csv','r'))
print(list(self.xyz))
csv = GetInstgramUsernames()
csv.read()
实际控制台输出
python xmen.py
D:\ProgramData\Anaconda2\lib\csv.pyc
[['user_name'], ['mensfashionpost'], ['creativefasion']]
Traceback (most recent call last):
File "xmen.py", line 25, in <module>
csv.read()
File "xmen.py", line 18, in read
self.xyz = csv.reader(open('D:\\dev\\scrapy\\instagram_influencers\\instagram_influencers\\input\\user_names.csv','r'))
AttributeError: 'GetInstgramUsernames' object has no attribute 'reader' D:\dev\scrapy\instagram_influencers>
答案 0 :(得分:0)
如果要向对象添加任何内容,则需要使用self
。那么,行
reader = csv.reader(open('D:\\dev\\scrapy\\instagram_influencers\\instagram_influencers\\input\\user_names.csv','r'))
应该说
self.reader = csv.reader(open('D:\\dev\\scrapy\\instagram_influencers\\instagram_influencers\\input\\user_names.csv','r'))
您会注意到您在对象初始化(__init__
部分)中执行了类似操作。
答案 1 :(得分:0)
我的错误与其他问题相似。
我没有名为csv.py
的文件,但我确实使用了名为csv
的变量名称。
感谢@ user2357112指出这一点