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

python command in script:

import zipfile

Output on screen

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$ 


Solution 1:[1]

You are trying to import the builtin zipfile module, but instead Python is trying to import a file in the current directory named zipfile.py. This is because of the Python Module Search Path

From the docs:

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 doesn't look in the directory where the builtin zipfile.py is because it finds work/zipfile.py first, which has invalid syntax and you probably don't want to be importing at all. The solution is to rename work/zipfile.py so Python can find the right file.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1