zoukankan      html  css  js  c++  java
  • python 文件目录操作

    在Python程序中执行目录和文件的操作

    Python内置的os模块可以直接调用操作系统提供的接口函数

    Python交互式命令行

    >>> import os
    >>> os.name # 操作系统类型
    'posix'
    如果是posix,说明系统是Linux、Unix或Mac OS X,如果是nt,就是Windows系统。

    合并、拆分路径的函数并不要求目录和文件要真实存在,它们只对字符串进行操作

     


    用Python的特性来过滤文件

    列出当前目录下的所有目录:

    >>> [x for x in os.listdir('.') if os.path.isdir(x)]
    ['.lein', '.local', '.m2', '.npm', '.ssh', '.Trash', '.vim', 'Applications', 'Desktop', ...]


    要列出所有的.py文件:

    >>> [x for x in os.listdir('.') if os.path.isfile(x) and os.path.splitext(x)[1]=='.py']
    ['apis.py', 'config.py', 'models.py', 'pymonitor.py', 'test_db.py', 'urls.py', 'wsgiapp.py']


    编写一个程序,能在当前目录以及当前目录的所有子目录下查找文件名包含指定字符串的文件,并打印出相对路径。
    def findFile(str, path='.'):
    for f in os.listdir(path):
    fPath = os.path.join(path, f)
    if os.path.isfile(fPath) and str in f:
    print(fPath)
    if os.path.isdir(fPath):
    findFile(str, fPath)

    朝闻道
  • 相关阅读:
    Zabbix——1
    Hive 基础知识——01
    Vim快捷命令
    Shell——2
    Shell——6
    Shell——4
    Shell——3
    Shell——1
    Hive 安装和配置以及基本语法——02
    Shell——5
  • 原文地址:https://www.cnblogs.com/wander-clouds/p/8471497.html
Copyright © 2011-2022 走看看