0

I have such a file

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

run it to produce the module path

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

I could get its path from internal code.

Then I open another 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'

If I change directories around couple of time and lost in the maze, and markdown file does not have internal code to help.

How could I get the path of "a_long_name_file.md"

AbstProcDo
  • 19,953
  • 19
  • 81
  • 138

1 Answers1

0

I don't think you can: the name attribute relates to the name the file was opened with, which in case of a relative name, will remain relative.

You should either open the file with the full path, or cheat a bit:

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

NB: see this question & answers on abspath and realpath.

9769953
  • 10,344
  • 3
  • 26
  • 37