为什么在Mac OS X 2.7.5中找不到Python 2.7中的文件? [英] Why can't I find a file in Python 2.7 on Mac OS X 2.7.5?

查看:370
本文介绍了为什么在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机器上工作得很好。

Works perfectly fine on my Windows 7 machine.

推荐答案

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

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))

请注意,Windows通常接受正斜杠作为路径分隔符以及使用Windows API时,只是CMD.EXE不接受它们。这就是为什么在Windows上, os.altsep 被设置为正斜杠(人们只是使用所有路径中的正斜杠,甚至在Windows上)。

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

这篇关于为什么在Mac OS X 2.7.5中找不到Python 2.7中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆