2016-01-13 40 views
0

我试图从脚本中使用openpyxl。Python IDLE openpyxl - 运行脚本时出现AttributeError

当从IDLE外壳采用openpyxl,一切顺利的话:

Python 2.7.9 |Anaconda 2.2.0 (32-bit)| (default, Dec 18 2014, 17:00:07) [MSC v.1500 32 bit (Intel)] on win32 
Type "copyright", "credits" or "license()" for more information. 
>>> import openpyxl as px 
>>> wb = px.workbook.Workbook() 
>>> 

,我可以使用所有其他openpyxl-功能。

然而,在脚本中把这个当...:

import openpyxl as px 
wb = px.workbook.Workbook() 

(注意,脚本被称为/另存为 'openpyxl_2.py')

和运行IDLE剧本,我得到以下错误:

Python 2.7.9 |Anaconda 2.2.0 (32-bit)| (default, Dec 18 2014, 17:00:07) [MSC v.1500 32 bit (Intel)] on win32 
Type "copyright", "credits" or "license()" for more information. 
>>> ================================ RESTART ================================ 
>>> 

Traceback (most recent call last): 
    File "\\verdc01\userdocs$\wkvdleeden\My Documents\Python excel\openpyxl_2.py", line 1, in <module> 
    import openpyxl as px 
    File "\\verdc01\userdocs$\wkvdleeden\My Documents\Python excel\openpyxl.py", line 8, in <module> 
AttributeError: 'module' object has no attribute 'workbook' 
>>> 

使用Python 2.7.9和2.3.2 openpyxl(很好地安装了PIP)。

问:

如何来从一个脚本运行,我得到上述错误? 如何让它工作?

邮政scriptum - 注意,我已经检查了以下主题: cannot import workbook in openpyxlImport error for openpyxlopenpyxl library - jdcal error

+0

尝试重命名文件的蟒蛇。看起来你已经将它命名为与模块名称相同。所以这个模块会被脚本“遮蔽”。 [见此](http://python-notes.curiousefficiency.org/en/latest/python_concepts/import_traps.html#the-name-shadowing-trap) – M4rtini

+0

@ M4rtini已经尝试过。为了好的措施,重新启动计算机以确保IDLE不会引用脚本的某种旧副本。但是,谢谢你的提示! – Willem

+0

因此错误输出中提到的文件被重命名? “\\ verdc01 \ userdocs $ \ wkvdleeden \ My Documents \ Python excel \ openpyxl.py” 您可以尝试打印出'px .__ file__'的输出以查看实际加载的模块。 – M4rtini

回答

1

的问题是在同一个文件夹命名为 “openpyxl.py” 的剧本。 导入openpyxl模块时,将导入此本地脚本\模块而不是全局模块。

重命名此文件,它应该工作。 print px.__file__确认哪个模块实际导入。

Another common trap, especially for beginners, is using a local module name that shadows the name of a standard library or third party package or module that the application relies on. One particularly surprising way to run afoul of this trap is by using such a name for a script, as this then combines with the previous “executing the main module twice” trap to cause trouble. For example, if experimenting to learn more about Python’s socket module, you may be inclined to call your experimental script socket.py. It turns out this is a really bad idea, as using such a name means the Python interpreter can no longer find the real socket module in the standard library, as the apparent socket module in the current directory gets in the way:

Source(Nick Coghlan's Python Notes)

相关问题