2014-01-08 61 views
0

使用下面的代码:为什么我无法在Mac OS X 2.7.5上的Python 2.7中找到文件?

fileName = 'Data\\all_earthquakes.csv' 
with open(fileName, 'rb') as csv_file: 
    attrHeaderRow = csv_file.readline().strip() 

我得到以下错误:

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

工作完全正常我的Windows 7机器上。

+0

我在想你为什么发布这个问题。 –

+0

因为我有这个问题,并通过发布问题中途找出它。决定回答它,以防有人遇到这个问题。我从来没有,我已经使用了5年的Python。 – Blairg23

回答

2

Windows和Mac OS X使用不同的字符分离路径中的元素。 Windows使用反斜杠,Mac OS X(和Linux/UNIX)使用正斜杠。 Python为您负责:使用os.path.join为当前操作系统使用正确的分隔符构建路径,如果需要用于路径分隔的实际字符,则使用os.sep

import os 
import sys 

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

注意使用Windows API时的Windows普遍接受斜杠作为路径分隔符,以及 - 它只是CMD.EXE,不接受他们。这就是为什么在Windows上,os.altsep被设置为正斜杠(并且人们只是在所有路径中使用正斜杠,即使在Windows中也是如此)。

1

你需要改变你的代码如下:

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

Mac OSX上使用不同的文件结构,这导致了差异向前或向后斜杠的目录名。

如果你想为此做了检查,使用下面的代码:

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 

更多信息可以在这里找到:

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

相关问题