当前位置: 首页 > 图文教程 > 脚本技术 > Python > py中的目录与文件判别代码

Python
Python入门教程 超详细1小时学会Python
复制粘贴功能的Python程序
python远程登录代码
Python Mysql自动备份脚本
py中的目录与文件判别代码
python下如何让web元素的生成更简单的分析
Python 文件操作技巧(File operation) 实例代码分析
python备份文件的脚本
Python备份Mysql脚本
rhythmbox中文名乱码问题解决方法
Python交换变量
Python字符遍历的艺术
Python字符转换
Python isinstance判断对象类型
Python ljust rjust center输出
Python strip lstrip rstrip使用方法
Python 连接字符串(join %)
Python 字符串中的字符倒转
Python translator使用实例
Python 除法小技巧

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


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-11   浏览: 83 ::
收藏到网摘: n/a

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