Why can't I find a file in Python 2.7 on Mac O

2019-09-06 02:26发布

问题:

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:

IOError: [Errno 2] No such file or directory: 'Data\\all_earthquakes.csv'

Works perfectly fine on my Windows 7 machine.

回答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).



回答2:

You need to change your code as follows:

fileName = 'Data/all_earthquakes.csv'
with open(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":
# linux
elif _platform == "darwin":
# OS X
elif _platform == "win32":
# Windows...
elif _platform == "cygwin":
#cygwin install

More information can be found here:

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