pythonfilepython-standalone

Handling usernames in file paths using Python


I'm writing a program that I would like to make a stand alone for my company. It works perfectly when I run it from the sublime text shell and I have everything set up to go except one issue that I can't seem to solve; file paths that involve usernames. Does anyone have any suggestion on how to handle this?

An example is wb.save(r'C:\Users******\Desktop\Excel.xlsx')

I want to make the ****** part either be automatic or an input box.


Solution

  • Use os.path.expanduser() with '~' where you want the home directory:

    import os
    print(os.path.expanduser('~/Desktop/Excel.xlsx'))
    

    Alternatively use pathlib.Path:

    from pathlib import Path
    print(Path.home() / 'Desktop' / 'Excel.xlsx')