python os.path.expanduser 的作用

python的os.path 模块提供了一个expanduser函数,它可以将参数中开头部分的 ~ 或 ~user 替换为当前用户的home目录并返回,仅看定义难以理解,我在linux系统和winodws系统下分别实验它的功能。

在linux系统下,我的账号是kwsy,这个用户的home目录是/home/kwsy,下面的代码演示如何使用expanduser函数。

Python 3.7.0 (default, Jun 28 2018, 13:15:42)
[GCC 7.2.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.path.expanduser('~/.config/')
'/home/kwsy/.config/'

目录 ~/.config/ 中,~本就是用户home目录的代表,如果你的账户是sheng, 那么在shell 里, ~/.config/ 就等价于 /home/sheng/.config,shell会帮你找到目录的绝对地址,但在python程序里,这种等价关系是不成立的,执行os.mkdir('~/test') 会报错,python不能将 ~/test 识别为/home/sheng/test, 这种情况下,就可以使用expanduser函数将~替换为当前用户的hone工作目录。

在windows下,我的账户名是zhangdongsheng, 工作目录就是C:\Users\zhangdongsheng

Python 3.6.8 (tags/v3.6.8:3c6b436a57, Dec 24 2018, 00:16:47) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.path.expanduser('~/.config/')
'C:\\Users\\zhangdongsheng/.config/'

扫描关注, 与我技术互动

QQ交流群: 211426309

加入知识星球, 每天收获更多精彩内容

分享日常研究的python技术和遇到的问题及解决方案