我在windows磁盘F:\debug\1文件下创建了一个test.py的python文件,下面在这个python代码中解释os.path.dirname(__file__),os.path.basename(_file_),os.path.abspath(_file_)等用法

1.os.path.abspath(file)
os.path.dirname(file) 返回脚本的绝对路径
# -*- coding: utf-8 -*-
import os
#os.path.abspath(__file__)返回的是.py文件的绝对路径(完整路径)
path2=os.path.abspath(__file__)
print('path2',path2)

2. os.path.dirname(file)
os.path.dirname(path) 返回path的父路径
# -*- coding: utf-8 -*-
import os
#组合使用
path3=os.path.dirname(os.path.abspath(__file__))
print('path3',path3)

3.os.path.basename(file)
os.path.basename(file) 返回脚本的文件名称
# -*- coding: utf-8 -*-
import os
# 返回脚本的文件名称
print(os.path.basename(__file__))

本文介绍了Python中os模块的几个关键路径操作函数,包括os.path.abspath()用于获取文件的绝对路径,os.path.dirname()用于获取文件的父目录,以及os.path.basename()用于获取文件名。通过示例代码详细展示了这三个函数的使用方法,帮助理解如何在Python中处理文件路径。
1万+

被折叠的 条评论
为什么被折叠?



