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

时间:2023-06-01 03:32:06 

>>> 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,目录,文件判别
0
投稿

猜你喜欢

  • 关于python环境变量如何配置

    2023-06-02 14:23:09
  • VS2013设置护眼背景颜色

    2023-06-28 12:59:02
  • Go语言快速入门图文教程

    2023-07-23 10:30:16
  • 10大实用web应用界面技术[译]

    2009-01-20 12:40:00
  • SQL Server中如何快速获取表的记录总数

    2008-12-05 15:59:00
  • python 列表推导式使用详解

    2021-10-13 01:53:28
  • Python代码列表求并集,交集,差集

    2021-12-03 03:33:38
  • Codeigniter发送邮件的方法

    2023-11-15 05:08:25
  • Python操作PDF文件之实现A3页面转A4

    2021-03-06 19:45:06
  • python-图片流传输的思路及示例(url转换二维码)

    2021-06-18 14:48:44
  • [翻译]标记语言和样式手册 chapter 5 表单

    2008-01-23 17:20:00
  • 解决Python列表字符不区分大小写的问题

    2022-09-10 20:43:52
  • python调用百度语音识别实现大音频文件语音识别功能

    2023-11-29 00:59:53
  • 学习ASP.NET八天入门:第三天

    2007-08-07 13:30:00
  • 如何使用yolov5输出检测到的目标坐标信息

    2021-07-12 17:25:14
  • 对PyQt5中的菜单栏和工具栏实例详解

    2021-12-13 19:03:33
  • Python基础 括号()[]{}的详解

    2023-07-22 07:35:39
  • Django 如何使用日期时间选择器规范用户的时间输入示例代码详解

    2023-06-18 23:56:20
  • JavaScript对象的property属性详解

    2024-05-05 09:22:57
  • 使用 Supervisor 监控 Python3 进程方式

    2021-06-21 11:48:13
  • asp之家 网络编程 m.aspxhome.com