如何转换〜/.通往绝对路径

如何转换〜/.通往绝对路径

问题描述:

我有以下文件:~/.config.txt,它位于/root/.config中.为了避免在Python文件中使用硬编码的路径,如何在Python中始终将~/路径替换为~/路径(并正确引用)? 这样,如果/root/是我的主目录,则可以用/root/.config替换~/.config.txt.

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?

您可以使用

You can use os.path.expanduser to convert ~ into your home directory:

>>> import os
>>> os.path.expanduser('~/.config.txt')
'/root/.config.txt'
>>>

这在* nix和Windows系统上均适用.

This works on both *nix and Windows systems.