检索打开的文件的路径

时间:2018-11-09 12:59:52

标签: python

我有这样的文件

In [24]: !cat test.py
print(f'The path is {__file__}')

运行它以生成模块路径

In [25]: run test.py
The path is /root/test.py

我可以从内部代码获取其路径。

然后我打开另一个a_long_name_file.py

In [43]:  f = open("a_long_name_file.md")

In [44]: cd .. #change the directory
/

In [45]: f.name
Out[45]: 'a_long_name_file.md'

如果我在数次左右更改目录却迷宫了,并且markdown文件没有内部代码可提供帮助。

如何获取“ a_long_name_file.md”的路径

1 个答案:

答案 0 :(得分:0)

我认为您不能:name属性与打开文件时使用的名称有关,如果使用相对名称,该名称将保持相对。

您应该使用完整路径打开文件,或者作弊:

In [1]: f = open("a_long_name_file.md")
In [2]: f.realpath = os.path.realpath(f.name)   # first thing after opening the file    
...
In [42]: cd ..
...
In [56]: f.realpath

注意:请参见this question & answers on abspath and realpath