OS操作文件或目录例子

1. 列出当前目录下的所有文件夹

[x for x in os.listdir('.') if os.path.isdir(x)]

2.列出当前目录下的所有文件

[x for x in os.listdir('.') if os.path.isfile(x)

3. 列出当前目录下所有python文件

[x for x in os.listdir('.') if os.path.isfile(x) and os.path.splittext()[1] == '.py']

4. 列出某路径下及其子文件夹下包含字符'a'的路径

import os

def get_path_for_key(path,key):
    #校验入参类型
    if isinstance(path,str) and isinstance(key,str):
        result = []   #存放所有答条件路径
        #列出所有目录和文件夹,循环判断
        for dir in os.listdir(path):
            fullpath = os.path.join(path, dir)
            #如果是文件类型及包含'a'返回
            if os.path.isfile(fullpath) and key in dir:
                result.append(fullpath)
            #如果是目录,再循环
            elif os.path.isdir(dir):
                get_path_for_key(fullpath, key)
        return result
    else:
        print('path和key需要都是字符类型')

if __name__ == '__main__':
    print(get_path_for_key('.','a'))

结果:['.\\runner_all.py']

猜你喜欢

转载自blog.csdn.net/hou_angela/article/details/83861902
今日推荐