栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python os.path.expanduser os.path.expandvars

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python os.path.expanduser os.path.expandvars

os.path.expanduser(path)
在linux平台下,可以用~来代表 "/home/你的用户名/" 这个路径。
那么python是不认识~这个符号的,如果你写路径的时候直接写 "~/pic" ,程序是执行不了的。
但是你非要用~,这时候这个os.path.expanduser就派上用场了,
os.path.expanduser("~/pic")它就把~展开,
从而得到一个这样的路径:
   "/home/你的用户名/pic"
在windows平台下,os.path.expanduser("~/pic")得到如下的路径:
  "C:UsersAdministrator/pic"
eg:
"""
os.path.expanduser(path) #返回字符串
"""
import os

path = r"C:UsersAdministratorDesktop"
print(os.path.expanduser(path))
print(os.path.expanduser("~"))
print(os.path.expanduser("~/pic"))
print(os.path.expanduser("~pic"))
print(os.path.expanduser("~\pic"))
print(os.path.expanduser("~/"))
print(os.path.expanduser("~pic"))
print(os.path.expanduser("~//pic"))
print(os.path.expanduser("~//pic"))
print(os.path.expanduser("/pic"))
print(os.path.expanduser("pic"))
输出结果(windows下):

os.path.expandvars(path)
可以获取到系统环境变量的值。
eg:
"""
os.path.expandvars(path) #返回字符串
"""
import os
path1 = r"%HOMEPATH%aa"
path2 = r"C:Users$USERNAMEaa"
path3 = r"${TEMP}aa"
path4 = r"${TEMP}aa"
path5 = r"%TEMP%aa"
path6 = r"$TEMPaa"
print(os.path.expandvars(path1))
print(os.path.expandvars(path2))
print(os.path.expandvars(path3))
print(os.path.expandvars(path4))
print(os.path.expandvars(path5))
print(os.path.expandvars(path6))
输出结果(windows下):

官方文档介绍:
os.path.expanduser(path)
os.path.expandvars(path)

https://docs.python.org/zh-cn/3/library/os.path.html#os.path.expanduser

-----结束------
仅学习。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/875841.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号