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.