当前位置: 移动技术网 > IT编程>脚本编程>Python > py中的目录与文件判别代码

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

2019年04月06日  | 移动技术网IT编程  | 我要评论

重生都市邪神,中国体育教师网,兽魔狐仙

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网