rzs rzs - 1 year ago 70
Python Question

Pandas not working in Downloads Directory

When I enter my

directory on Mac OSX (10.9.5), I entered Python from my terminal and tried to import pandas using
import pandas as pd

name:Downloads name$ python
Python 2.7.5 (default, Mar 9 2014, 22:15:05)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pandas as pd
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Python/2.7/site-packages/pandas/__init__.py", line 22, in <module>
from pandas.compat.numpy import *
File "/Library/Python/2.7/site-packages/pandas/compat/__init__.py", line 38, in <module>
import inspect
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/inspect.py", line 39, in <module>
import tokenize
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/tokenize.py", line 30, in <module>
from token import *
File "token.py", line 7, in <module>
reader = csv.reader(open('ebook.csv', 'rb'))
IOError: [Errno 2] No such file or directory: 'ebook.csv'

In other directories I've tried though, this seems to import pandas just fine without complaint (including random System directories, the home directory and my ~/Documents directory).

Why is ebook.csv a problem simply in the Downloads?

Answer Source

It looks like you have a file called token.py in your Downloads directory. It is getting imported instead of the token.py module from the standard library:

  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/tokenize.py", line 30, in <module>
    from token import *
  File "token.py", line 7, in <module>
    reader = csv.reader(open('ebook.csv', 'rb'))

The solution is to rename the Downloads/token.py file to it does not shadow the standard library module of the same name.

Above, the line

from token import *

tells Python to import the token module. Usually, Python would find the token module from the standard library, /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/token.py.

The directory from which you launch Python is inserted as the first directory in sys.path. Python searches sys.path for modules in the order they are listed. When you launch Python from the Downloads directory, this directory becomes the first directory searched by Python for modules. So your Downloads/token.py file is getting imported instead of the /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/token.py (standard library) file.

Conclusion: Never name a file the same as any module from the standard library.