pythonlinuxstringjoinpath-manipulation

Python os.path.join absolute path on Linux


I have a file path like this:

file_name = full_path + env + '/filename.txt'

in which:

=> file name is '/home/louis/key-files/prod/filename.txt'

I want to use os.path.join

file_name = os.path.abspath(os.path.join(full_path, env, '/filename.txt'))

But the returned result is only: file_name = '/filename.txt'

How can I get the expected result like above? Thanks


Solution

  • Since your last component begins with a slash, it is taken as starting from the root, so os.path.join just removes everything else. Try without the leading slash instead:

    os.path.join(full_path, env, 'filename.txt')
    

    Note you probably don't need abspath here.