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中redis查看剩余过期时间及用正则通配符批量删除key的方法

具体代码如下所示: # -*- coding: utf-8 -*- import redis import datetime ''' # 1. redis设置过期时间的两种方式 e...

python pandas cumsum求累计次数的用法

python pandas cumsum求累计次数的用法

本文主要是针对 cumsum函数的一些用法。具体应用场景看下面的数据集。 第一列是userID,第二列是安装的时间,第三列是安装的次数。 我们现在想做一件事情。就是统计用户在某一天前...

Win10+GPU版Pytorch1.1安装的安装步骤

Win10+GPU版Pytorch1.1安装的安装步骤

安装cuda 更新nvidia驱动 打开GeForce Game Ready Driver或在GeForce Experience中下载符合自己gpu的程序。 选择cuda 打开nvi...

python实现的config文件读写功能示例

本文实例讲述了python实现的config文件读写功能。分享给大家供大家参考,具体如下: 1、设置配置文件 [mysql] host = 1234 port = 3306 user...

Django 实现Admin自动填充当前用户的示例代码

model.py import datetime from django.contrib.auth.models import User from django.db import...