python文件路径的操作
python文件路径的操作
在python中,文件使用十分频繁,本文将向大家介绍python文件路径的操作:得到指定文件路径、得到当前文件名、判断文件路径是否存在、获得指定文件夹下所有文件、获得文件后缀、拼接路径和文件名。
1、得到指定文件路径:os.path.dirname(带路径文件名)
查找处理文件要调用os库,和openpyxl一样,先用import导入。
importos
file=r’e:\python\删除最小值.xlsx’
pwd=os.path.dirname(file)
print(pwd)
运行结果为:
e:\python
也可从分离文件名后的列表中提取:os.path.split(带路径文件名)[0]
2、得到当前文件名:os.path.dasename(带路径文件名)
importos
file=r’e:\python\删除最小值.xlsx’
pwdn=os.path.basename(file)
print(pwdn)
运行结果为:
删除最小值.xlsx
也可从分离文件名后的列表中提取:os.path.split(带路径文件名)[1]
3、判断文件路径是否存在:os.path.exists(带路径文件名)
importos
file=r’e:\python\删除最小值.xlsx’
pwdbool=os.path.exists(file)
print(pwdbool)
运行结果为:
true
若给定的路径文件不存在,则返回false
4、获得指定文件夹下所有文件:print(os.listdir(文件夹路径))
importos
pwdns=os.listdir(r’e:\python’)
print(pwdns[1])
运行结果:
8.py为’e:\python’文件夹下第2个文件(或文件夹)名。
5、获得文件后缀:os.path.splitext(文件名)
importos
pdn=os.path.splitext(‘试验.py’)
print(pdn[1])
运行结果:
.py,若最后一句改为print(pdn[0]),则得到文件名。
6、拼接路径和文件名:os.path.join(路径,文件名)
f2=os.path.join(f1,‘汇总.xlsx’)
运行结果:
‘e:\python\汇总\汇总.xlsx’
以上就是python文件路径操作的介绍了,希望能对你有所帮助哦~更多Python学习教程请关注IT培训机构:千锋教育。

相关推荐HOT
更多>>
python装饰器管理函数和类的注意点
python装饰器管理函数和类的注意点本文教程操作环境:windows7系统、Python3.9.1,DELLG3电脑。1、注意点(1)用装饰器修饰的函数或类主要应用场...详情>>
2023-11-07 21:15:48
python输入数字变成月份
python输入数字变成月份1、思路说明可计算给定区间的时间差,即两者之间共包含几个月。然后由第一个月(开始时间)逐渐累积,最后得到给定时间区...详情>>
2023-11-07 18:13:40
pythonGevent的使用
1、可以通过gevent轻松实现并发同步或异步编程。gevent中使用的主要模式是Greenlet,它是以C扩展模块的形式访问Python的轻量级协程。2、Greenle...详情>>
2023-11-07 17:51:06
python怎么生成xml文件
用python内置的xml.dom可以对xml文件进行解析处理。什么是xml?XML指可扩展标记语言(EXtensibleMarkupLanguage)XML是一种标记语言,很类似HTMLXM...详情>>
2023-11-07 16:53:54热门推荐
技术干货






