python的目录操作,os,os.path

设定项目路径为:E:\StudySpace\pythonStudySpace
文件路径为:E:\StudySpace\pythonStudySpace\try_os\try_os.py

# 获取当前脚本文件所在的目录绝对路径
os.path.abspath(os.path.dirname(__file__))
# 获取当前脚本上级目录
os.path.dirname(os.path.dirname(__file__))


# 获取python运行的目录,非文件所在目录
# C:\test\>python E:\StudySpace\pythonStudySpace\try_os\try_os.py
# 结果是 C:\test
path = os.getcwd()

# 返回文件路径,有可能是相对路径,也可能是绝对路径,建议使用abspath或realpath
print(__file__)

# 返回文件绝对路径
# 区别:对于linux里的链接文件,abspath返回链接文件绝对路径,realpath返回的是链接文件所指文件的绝对路径
print(os.path.abspath(__file__))
print(os.path.realpath(__file__))

# 相同与path = os.getcwd()
print(os.path.abspath(''))
print(os.path.realpath(''))

# 获取文件路径中的目录部分:E:\StudySpace\pythonStudySpace
print(os.path.dirname(os.path.abspath(__file__)))

# 判断路径是否存在
os.path.exists(path)

# 更多os.path操作
os.path.abspath(path) #返回绝对路径
os.path.basename(path) #返回文件名
os.path.commonprefix(list) #返回list(多个路径)中,所有path共有的最长的路径。
os.path.dirname(path) #返回文件路径
os.path.exists(path)  #路径存在则返回True,路径损坏返回False
os.path.lexists  #路径存在则返回True,路径损坏也返回True
os.path.expanduser(path)  #把path中包含的"~"和"~user"转换成用户目录
os.path.expandvars(path)  #根据环境变量的值替换path中包含的”$name”和”${name}”
os.path.getatime(path)  #返回最后一次进入此path的时间。
os.path.getmtime(path)  #返回在此path下最后一次修改的时间。
os.path.getctime(path)  #返回path的大小
os.path.getsize(path)  #返回文件大小,如果文件不存在就返回错误
os.path.isabs(path)  #判断是否为绝对路径
os.path.isfile(path)  #判断路径是否为文件
os.path.isdir(path)  #判断路径是否为目录
os.path.islink(path)  #判断路径是否为链接
os.path.ismount(path)  #判断路径是否为挂载点()
os.path.join(path1[, path2[, ...]])  #把目录和文件名合成一个路径
os.path.normcase(path)  #转换path的大小写和斜杠
os.path.normpath(path)  #规范path字符串形式
os.path.realpath(path)  #返回path的真实路径
os.path.relpath(path[, start])  #从start开始计算相对路径
os.path.samefile(path1, path2)  #判断目录或文件是否相同
os.path.sameopenfile(fp1, fp2)  #判断fp1和fp2是否指向同一文件
os.path.samestat(stat1, stat2)  #判断stat tuple stat1和stat2是否指向同一个文件
os.path.split(path)  #把路径分割成dirname和basename,返回一个元组
os.path.splitdrive(path)   #一般用在windows下,返回驱动器名和路径组成的元组
os.path.splitext(path)  #分割路径,返回路径名和文件扩展名的元组
os.path.splitunc(path)  #把路径分割为加载点与文件
os.path.walk(path, visit, arg)  #遍历path,进入每个目录都调用visit函数,visit函数必须有
3个参数(arg, dirname, names),dirname表示当前目录的目录名,names代表当前目录下的所有
文件名,args则为walk的第三个参数
os.path.supports_unicode_filenames  #设置是否支持unicode路径名
os.pardir  #当前目录的父目录

os.path.join(script_dir, os.pardir, os.pardir)  #script_dir的祖父目录,例如:script_dir是F:\1\2\3,那么os.path.join(script_dir, os.pardir, os.pardir)是F:\1\2\3\..\..

os.path.abspath(os.path.join(script_dir, os.pardir, os.pardir)) #script_dir的祖父目录,例如:script_dir是F:\1\2\3,那么os.path.abspath(os.path.join(script_dir, os.pardir, os.pardir))是F:\1
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值