How to convert ~/. path to absolute path

2019-06-20 13:42发布

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条回答
放我归山
2楼-- · 2019-06-20 14:37

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.

查看更多
登录 后发表回答