问题
I have the following file: ~/.config.txt which is located in /root/.config. In order to avoid hardcoded paths in my Python file, how can I always replace (and correctly refer) to a ~/ path as <home> in Python?
This way I could replace ~/.config.txt by /root/.config if /root/ was my home directory?
回答1:
You can use os.path.expanduser to convert ~ into your home directory:
>>> import os
>>> os.path.expanduser('~/.config.txt')
'/root/.config.txt'
>>>
This works on both *nix and Windows systems.
来源:https://stackoverflow.com/questions/27849003/how-to-convert-path-to-absolute-path