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

yipeiwu_com4年前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']
>>>

相关文章

pyqt 多窗口之间的相互调用方法

* 在编程开发中,一个程序不可避免的需要多窗口操作来实现具体的功能。 实现此功能的基本步骤(以三个窗口为例,使用主窗口调用其它两个窗口) # 主窗口 from PyQt5 impor...

django+xadmin+djcelery实现后台管理定时任务

django+xadmin+djcelery实现后台管理定时任务

继上一篇中间表的数据是动态的,图表展示的数据才比较准确。这里用到一个新的模块Djcelery,安装配置步骤如下: 1.安装 redis==2.10.6 celery==3.1.23 dj...

使用Python中PDB模块中的命令来调试Python代码的教程

你有多少次陷入不得不更改别人代码的境地?如果你是一个开发团队的一员,那么你遇到上述境地的次数比你想要的还要多。然而,Python中有一个整洁的调试特性(像其他大多数语言一样),在这种情况...

Python中那些 Pythonic的写法详解

前言 Martin(Bob大叔)曾在《代码整洁之道》一书打趣地说:当你的代码在做 Code Review 时,审查者要是愤怒地吼道: “What the fuck is this shi...

python3+opencv3识别图片中的物体并截取的方法

如下所示: 运行环境:python3.6.4 opencv3.4.0 # -*- coding:utf-8 -*- """ Note: 使用Python和OpenCV检测...