在 python 2.7 中导入 zipfile 模块时出现语法错误

I am getting a syntax error while importing the zipfile module in python 2.7

python 脚本中的命令:

import zipfile

在屏幕上输出

Chetans-MacBook-Pro:work chetankshetty$ python myprog.py
Traceback (most recent call last):
  File "myprog.py", line 1, in <module>
    import zipfile
  File "/Users/chetankshetty/Documents/Work/zipfile.py", line 1
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
    ^
SyntaxError: invalid syntax

Chetans-MacBook-Pro:work chetankshetty$ 

您正在尝试导入内置 zipfile 模块,但 Python 正在尝试导入当前目录中名为 zipfile.py 的文件。这是因为 Python Module Search Path

来自文档:

When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. sys.path is initialized from these locations:

  • the directory containing the input script (or the current directory).
  • PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
  • the installation-dependent default.

After initialization, Python programs can modify sys.path. The directory containing the script being run is placed at the beginning of the search path, ahead of the standard library path. This means that scripts in that directory will be loaded instead of modules of the same name in the library directory. This is an error unless the replacement is intended. See section Standard Modules for more information.

Python 不查找内置 zipfile.py 所在的目录,因为它首先找到 work/zipfile.py,它的语法无效,您可能不想完全是进口的。解决方案是重命名 work/zipfile.py 以便 Python 可以找到正确的文件。