在Python 3中导入模块时出现AttributeError [英] AttributeError when importing modules in Python 3

查看:288
本文介绍了在Python 3中导入模块时出现AttributeError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个使用json和请求模块的脚本.在编写脚本之前,我一直在交互式外壳上使用命令,并且由于为我的代码创建了实际文件,所以一切都以某种方式破坏了.第一次运行代码时,文件夹中出现了一个 pycache 文件夹,我认为这一切都破灭了.当在外壳中逐行运行该代码时,此 pycache 文件夹的存在也不再起作用.我的代码如下:

I am trying to write a script that makes use of the json and requests modules. Before I wrote the script, I was playing around with commands on the interactive shell, and since creating an actual file for my code, everything has somehow broken. The first time I ran the code, a pycache folder appeared in the folder and I think that is somehow breaking everthing. The code, when run line by line in the shell, no longer works either with the presence of this pycache folder. My code is as follows:

import json
import requests
r = requests.get('http://api.wunderground.com/api/78c2f37e6d924b1b/hourly/q/CA/Berkeley.json')
data = json.loads(r.text)
for x in range(0, 35):
    print(data['hourly_forecast'][x]['FCTTIME']['hour'])

这应该打印出天气预报中的所有时间,但是我得到一个"AttributeError:'module'对象没有属性'dumps'.在此文件夹中,我以前还拥有另一个使用外部模块的程序,该程序也没有可以在 pycache 文件夹中使用,因此我几乎可以肯定这是造成问题的原因.但是,删除它并不能解决任何问题,因为代码仍然无法使用,只是重新创建.

This should print out all the hours in the weather forecast, but I get an "AttributeError: 'module' object has no attribute 'dumps'. In this folder, I also previously had another program that used external modules that also no long works with the presence of the pycache folder, so I am almost certain that it is causing the problems. However, deleting it doesn't fix anything as the code still doesn't work, and it just gets recreated.

通过删除整个错误目录并重写所有内容,解决了该问题.

The problem was solved by deleting the entire buggy directory and rewriting everything.

推荐答案

'module' object has no attribute 'xxx'的最常见原因是:"xxx"是您知道"模块"具有的属性,原因是:您的程序是在目录中,您已经忘记了该模块的"module.py".因此,import module导入模块而不是stdlib(或其他地方)中的预期模块.在python-list上发布了多个有关此问题的示例.至少有两个是由于同一目录中被遗忘的random.py所致.

The most common reason for 'module' object has no attribute 'xxx', where 'xxx' is an attribute that you 'know' 'module' does have, is this: your program is in a directory that has a 'module.py' that you have forgotten about for the modment. So import module imports your module instead of the intended module in the stdlib (or elsewhere). There have been multiple examples of this problem posted on python-list. At least two were due to a forgotten-about random.py in the same directory.

如果您发布了追溯,情况将会更加清楚.

The situation would have been clearer if you had posted the traceback.

这篇关于在Python 3中导入模块时出现AttributeError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆