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

>>> 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’] >>>

Posted in 未分类

发表评论