西儿马 | python的path问题:No such file or directory

iPyhon里演练《利用Python进行数据分析》中的示例:来自bit.ly的1.usa.gov数据。代码很简单:

In [3]:path = ‘~/Documents/pydata-book/ch02/usagov_bitly_data2012-03-16-1331923249.txt’

In [4]:open(path).readline()

不料,却得到这么个错误结果:

IOError: [Errno 2] No such file or directory: ‘~/Documents/pydata-book/ch02/usagov_bitly_data2012-03-16-1331923249.txt’

又去看了一下路径和文件名,确实没有写错,那看起来是相对路径和绝对路径的问题了。

stackoverflow有类似的问题描述,有个回复写的非常浅显易懂:

You are using a relative path, which means that the program looks for the file in the working directory. The error is telling you that there is no file of that name in the working directory.

Try using the exact, or absolute, path.

那么,在Mac里,我们这个文件的绝对路径应该怎么描述呢?

试了几次,成功了:

In [11]:path = ‘/Users/username/Documents/pydata-book/ch02/usagov_bitly_data2012-03-16-1331923249.txt’

    原文作者:西儿马
    原文地址: https://www.jianshu.com/p/61381ff9ed71
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞