Why can't I find a file in Python 2.7 on Mac OS X 2.7.5?

核能气质少年 提交于 2019-12-12 02:15:39

问题


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



来源:https://stackoverflow.com/questions/20989554/why-cant-i-find-a-file-in-python-2-7-on-mac-os-x-2-7-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!