您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在平时处理文件的时候,都会用到模块os,今天运用os模块获取绝对路径下的文件的文件名和后缀名,这里测试文件为:
[root@python ~]# cat testfile /usr/local/application/website/test.txt /usr/local/application/website/test.txt /usr/local/bin/test.sh /usr/local/application/img/AEAFFEAG.jpg /usr/local/application/img/AEAFAGEAG.jpg /usr/local/application/CSS/up.css /usr/local/application/PNG/good.png /usr/local/application/img/AETTTGEAG.jpg /usr/local/application/CSS/main.css /usr/local/application/GIF/hello.gif /usr/local/application/js/foot.js [root@python ~]#
接下来编写脚本:
[root@python ~]# cat get_file_name.py #!/usr/bin/env python import os with open('/root/testfile','r') as obj: for line in obj: print os.path.splitext(line.strip()) [root@python ~]#
运行脚本输出结果:
[root@python ~]# python get_file_name.py ('/usr/local/application/website/test', '.txt') ('/usr/local/application/website/test', '.txt') ('/usr/local/bin/test', '.sh') ('/usr/local/application/img/AEAFFEAG', '.jpg') ('/usr/local/application/img/AEAFAGEAG', '.jpg') ('/usr/local/application/CSS/up', '.css') ('/usr/local/application/PNG/good', '.png') ('/usr/local/application/img/AETTTGEAG', '.jpg') ('/usr/local/application/CSS/main', '.css') ('/usr/local/application/GIF/hello', '.gif') ('/usr/local/application/js/foot', '.js') [root@python ~]#
从以上可以看出,每一行为一个元组,然后继续修改get_file_name文件:
[root@python ~]# cat get_file_name.py #!/usr/bin/env python # -*- coding:utf8 -*- import os with open('/root/testfile','r') as obj: for line in obj: print "文件路径为:%s 文件后缀为:%s" %(os.path.splitext(line.strip())[0],os.path.splitext(line.strip())[1]) [root@python ~]#
再运行脚本查看结果:
[root@python ~]# python get_file_name.py 文件路径为:/usr/local/application/website/test 文件后缀为:.txt 文件路径为:/usr/local/application/website/test 文件后缀为:.txt 文件路径为:/usr/local/bin/test 文件后缀为:.sh 文件路径为:/usr/local/application/img/AEAFFEAG 文件后缀为:.jpg 文件路径为:/usr/local/application/img/AEAFAGEAG 文件后缀为:.jpg 文件路径为:/usr/local/application/CSS/up 文件后缀为:.css 文件路径为:/usr/local/application/PNG/good 文件后缀为:.png 文件路径为:/usr/local/application/img/AETTTGEAG 文件后缀为:.jpg 文件路径为:/usr/local/application/CSS/main 文件后缀为:.css 文件路径为:/usr/local/application/GIF/hello 文件后缀为:.gif 文件路径为:/usr/local/application/js/foot 文件后缀为:.js [root@python ~]#
这里主要是运用os模块的splitext函数功能,以'.'的分隔符将一个完整的文件进行分割成元组,然后通过元组的下标获取元组中的元素。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。