如何在Python解释器中读取文件?

时间:2015-01-22 10:52:42

标签: python

如何在Python解释器中读取文件?

我想

f = open("~/jobs/2014-12-16/output/output.log", "r")

在Python交互式Shell中。怎么样?

获得:

IOError: [Errno 2] No such file or directory: '~/jobs/2014-12-16/output/output.log'

如果在父工作目录中启动了Interpreter,则无法使用路径。

2 个答案:

答案 0 :(得分:1)

交互式python和非交互式python之间没有(很好,非常小)的区别。您的问题是该文件不存在,如错误消息中所述。 Python不会自动扩展路径中的~字符,您必须使用os.path.expanduser函数。

f = open(os.path.expanduser("~/jobs/2014-12-16/output/output.log"), "r")

答案 1 :(得分:1)

你需要通过os.path.expanduser告诉Python尊重〜字符。

full_path = os.path.expanduser("~/jobs/2014-12-16/output/output.log")
f = open(full_path, 'r')