简体   繁体   中英

Python IDLE openpyxl - AttributeError when running script

I'm trying to use openpyxl from a script.

When using openpyxl from an IDLE shell, all goes well:

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()
>>> 

and I can use all other openpyxl-functionalities.

However, when putting this in a script...:

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

(note that the script is called/saved as 'openpyxl_2.py')

and running the script in IDLE, I get the following error:

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'
>>>

Using Python 2.7.9 and openpyxl 2.3.2 (nicely installed with pip).

Question:

How comes that running from a script I get the above error? How to get it working?

Post scriptum - note that I already checked the following topics: cannot import workbook in openpyxl , Import error for openpyxl , openpyxl library - jdcal error

The problem is the script named "openpyxl.py" in the same folder. When importing the openpyxl module, this local script\\module will be imported instead of the global module.

Rename this file and it should work. print px.__file__ to confirm which module is actually imported.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM