2016-01-13 38 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)

相關問題