西儿马 | 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'

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容