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

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

相关文章

Python zip函数打包元素实例解析

这篇文章主要介绍了Python zip函数打包元素实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 介绍 zip() 函数用于...

python操作MySQL数据库具体方法

复制代码 代码如下: import MySQLdbtry:    conn=MySQLdb.connect(host='localhost',user='r...

python实现二级登陆菜单及安装过程

python实现二级登陆菜单及安装过程

python实现二级登陆菜单的代码如下所示: """ 1.三级菜单 注册 登陆 注销 2.进入每一个一级菜单,都会有下一级的菜单 """ user_item = dict() t...

python3解析库pyquery的深入讲解

前言 pyquery是一个类似jquery的python库,它实现能够在xml文档中进行jQuery查询,pyquery使用lxml解析器进行快速在xml和html文档上操作,它提供了和...

python批量下载网站马拉松照片的完整步骤

python批量下载网站马拉松照片的完整步骤

前言 目前学习python几个月了,由于自己比较喜欢跑马拉松,已经跑过了很多场比赛,前些天就写了个简单的爬虫爬取了网上三千多场马拉松比赛的报名信息。 今年5月27日,我又参加了巴图鲁...