Reputation: 962
How can I get my script's file name as a relative path to cwd
and it being OS independent?
e.g if I'm in linux it should return "./script.py" and if I'm in windows it should return ".\\script.py"
I tried with os.path.join
and os.path.basename(__file__)
but it returns absolute path.
Upvotes: 1
Views: 552
Reputation: 1055
Why not simply let os
handle that for you?
path = os.path.normcase(os.path.join('.', os.path.relpath(__file__)))
Upvotes: 0
Reputation: 407
import os
import platform
path = os.path.basename(__file__)
run_on=platform.system()
if run_on=='Windows': path=f'.\\{path}'
elif run_on=='Linux': path=f'./{path}'
print(f'path is {path}')
Upvotes: 2