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

时间:2021-05-23

>>>importos导入模块
>>>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']
>>>[fforfinos.listdir(dirname)筛选出一个list,存放filename
ifos.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']
>>>[fforfinos.listdir(dirname)筛选出一个list,存放dirname
ifos.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

IDLE1.2.1
>>>importglob
>>>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']
>>>

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章