欢迎来到资源库(www.zyku.net)

Python教程

当前位置:首页 > 网络编程 > Python教程 > Python

Python中的目录与文件判别代码

时间:2021-04-24|栏目:Python教程|点击:|我要投稿
>>> import os                     导入模块
>>> os.listdir("d:\\python25")         列出所有目录和文件
['w9xpopen.exe', 'README.txt', 'NEWS.txt', 'LICENSE.txt', 'python.exe', 'pythonw.exe', 'Lib', 'DLLs', 'include', 'libs', 'tcl', 'Tools', 'Doc', 'odbchelper.py', 'odbchelper.pyc', 'test.log', 'sqlConnection.py', 'sqlConnection.pyc']
>>> dirname="d:\\python25"         支持自定义
>>> os.listdir(dirname)
['w9xpopen.exe', 'README.txt', 'NEWS.txt', 'LICENSE.txt', 'python.exe', 'pythonw.exe', 'Lib', 'DLLs', 'include', 'libs', 'tcl', 'Tools', 'Doc', 'odbchelper.py', 'odbchelper.pyc', 'test.log', 'sqlConnection.py', 'sqlConnection.pyc']
>>> [f for f in os.listdir(dirname)               筛选出一个list,存放filename
    if os.path.isfile(os.path.join(dirname, f))]
['w9xpopen.exe', 'README.txt', 'NEWS.txt', 'LICENSE.txt', 'python.exe', 'pythonw.exe', 'odbchelper.py', 'odbchelper.pyc', 'test.log', 'sqlConnection.py', 'sqlConnection.pyc']
>>> [f for f in os.listdir(dirname)              筛选出一个list,存放dirname
    if os.path.isdir(os.path.join(dirname, f))]
['Lib', 'DLLs', 'include', 'libs', 'tcl', 'Tools', 'Doc']

判别的应用

>>> os.path.isdir("D:\\")
True
>>> os.path.isdir("D:\\python25\\odbchelper.py")
False
>>> os.path.isfile("D:\\python25\\odbchelper.py")
True

当前目录

>>> os.getcwd()
'D:\\Python25'

通配符的使用,引入glob

IDLE 1.2.1      
>>> import glob
>>> glob.glob('D:\\python25\\*.exe')
['D:\\python25\\w9xpopen.exe', 'D:\\python25\\python.exe', 'D:\\python25\\pythonw.exe']
>>> glob.glob('D:\\python25\\py*.exe')
['D:\\python25\\python.exe', 'D:\\python25\\pythonw.exe']
>>>

(资源库 www.zyku.net)

上一篇:python远程登录代码

栏    目:Python教程

下一篇:python下如何让web元素的生成更简单的分析

本文标题:Python中的目录与文件判别代码

本文地址:https://www.zyku.net/python/2168.html

关于我们 | 版权申明 | 寻求合作 |

重要申明:本站所有的文章、图片、评论等内容,均由网友发表或上传并维护或收集自网络,仅供个人学习交流使用,版权归原作者所有。

如有侵犯您的版权,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:95148658 | 邮箱:mb8#qq.com(#换成@)

苏ICP备2020066115号-1

本网站由提供CDN加速/云存储服务