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 pillow模块使用方法详解

pillow Pillow是PIL的一个派生分支,但如今已经发展成为比PIL本身更具活力的图像处理库。pillow可以说已经取代了PIL,将其封装成python的库(pip即可安装),...

Python使用tkinter模块实现推箱子游戏

Python使用tkinter模块实现推箱子游戏

前段时间用C语言做了个字符版的推箱子,着实是比较简陋。正好最近用到了Python,然后想着用Python做一个图形界面的推箱子。这回可没有C那么简单,首先Python的图形界面我是没怎么...

Python模块文件结构代码详解

本文研究的主要是Python模块文件结构的相关内容,具体如下。 Python文件结构 文件结构(范例全文) #/usr/bin/env python "this is a...

Python中的二叉树查找算法模块使用指南

python中的二叉树模块内容: BinaryTree:非平衡二叉树  AVLTree:平衡的AVL树  RBTree:平衡的红黑树 以上是用python写的,相面...

Python使用xlwt模块操作Excel的方法详解

Python使用xlwt模块操作Excel的方法详解

本文实例讲述了Python使用xlwt模块操作Excel的方法。分享给大家供大家参考,具体如下: 部分摘自官网文档. 该模块安装很简单 $ pip install xlwt 先...