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实现翻转棋游戏(othello)

python实现翻转棋游戏(othello)

利用上一篇的框架,再写了个翻转棋的程序,为了调试minimax算法,花了两天的时间。 几点改进说明: 拆分成四个文件:board.py,player.py,ai.py,othell...

深入讲解Python编程中的字符串

深入讲解Python编程中的字符串

Python转义字符 在需要在字符中使用特殊字符时,python用反斜杠(\)转义字符。如下表: Python字符串运算符 下表实例变量a值为字符串"Hello",b变量值为"Pyt...

Jacobi迭代算法的Python实现详解

import numpy as np import time 1.1 Jacobi迭代算法 def Jacobi_tensor_V2(A,b,Delta,m,n,M): st...

Python高级特性与几种函数的讲解

切片 从list或tuple中取部分元素。 list = [1, 2, 3, 4] list[0 : 3] # [1, 2, 3] list[-2 : -1] # -1表示最后一个,...

Python使用面向对象方式创建线程实现12306售票系统

目前python 提供了几种多线程实现方式 thread,threading,multithreading ,其中thread模块比较底层,而threading模块是对thread做了一...