Search code examples
pythonpython-3.xabsolute-path

Absolute linking in Python


How can I make my links relative to the home directory (absolute linking)? I have a program that will use a file given anywhere in my user account. Code:

file_name = input("Enter file path")
try:
    file = open("../" + file_name)
    print(file)
except:
    print("Failed to open")

Currently this assumes my program is in my desktop (which it is). Can I make it so that it will work the same regardless of how many folders it is in?

EDIT: I want to make it relative to the user's home directory.


Solution

  • import os
    

    home_dir = os.path.expanduser('~')

    file_name = input("Enter file path")
    try:
        file = open(os.path.join(home_dir, file_name))
        print(file)
    except:
        print("Failed to open")
    

    os.path.expanduser('~') should return the home directory of the user.

    Though I can't quite tell if you want an absolute or relative path, and whether its to the home directory or your desktop directory that you want. You may want to reword your question.