Skip to content Skip to sidebar Skip to footer

Why Can't I Find A File In Python 2.7 On Mac Os X 2.7.5?

Using the following code: fileName = 'Data\\all_earthquakes.csv' with open(fileName, 'rb') as csv_file: attrHeaderRow = csv_file.readline().strip() I get the following error:

Solution 1:

Windows and Mac OS X use different characters to separate elements in paths. Windows uses the backslash, Mac OS X (and Linux/UNIX) uses the forward slash. Python takes care of this for you: use os.path.join to build paths using the correct separator for the current operating system or use os.sep if you need the actual character that is used for path separation.

import os
import sys

fileName = os.path.join('Data', 'all_earthquakes.csv')
print('Directory separator on your platform ({}): {}'.format(sys.platform, os.sep))

Note that Windows generally accepts the forward slash as path separator as well when using Windows APIs - it's just CMD.EXE that does not accept them. That's why on Windows, os.altsep is set to the forward slash (and people just use the forward slash in all paths, even on Windows).

Solution 2:

You need to change your code as follows:

fileName = 'Data/all_earthquakes.csv'withopen(fileName, 'rb') as csv_file:
    attrHeaderRow = csv_file.readline().strip()

Mac OSX uses a different file structure, which leads to the difference in forward or backward slashes in the directory name.

If you want to do a check for this, use the following code:

from sys import platform as _platform
if _platform == "linux"or _platform == "linux2":
# linuxelif _platform == "darwin":
# OS Xelif _platform == "win32":
# Windows...elif _platform == "cygwin":
#cygwin install

More information can be found here:

http://docs.python.org/2/library/platform.html

Post a Comment for "Why Can't I Find A File In Python 2.7 On Mac Os X 2.7.5?"