如何转换〜/.通往绝对路径 [英] How to convert ~/. path to absolute path

查看:67
本文介绍了如何转换〜/.通往绝对路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下文件:~/.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.

这篇关于如何转换〜/.通往绝对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆