How to convert ~/. path to absolute path

笑着哭i 提交于 2020-01-03 15:19:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!