Python之操作文件和目录

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

# coding=utf-8
# 在指定目录以及指定目录的所有子目录下查找文件名包含指定字符串的文件,并打印出相对路径
import os  # 导入os模块


def findfiles(dirfile, zdstr):
    for x in os.listdir(dirfile):  # os.listdir()列出所有目录和文件
        # os.path.isfile() 判断是否为文件 os.path.join() 把两个路径合成一部分
        if os.path.isfile(os.path.join(dirfile, x)):
            if x.find(zdstr) >= 0:  # 查找文件名包含指定字符串的文件
                print((os.path.join(dirfile, x).split('文件1\\')[1]))  # 打印出相对路径,注意\\是正则表达式的内容
        else:
            findfiles(os.path.join(dirfile, x), '2')  # 运用递归函数


findfiles('F:/文件1', '2')
# 执行结果:文件2\2.txt

创建的目录文件:

posted @ 2018-12-11 22:34  lengjf  阅读(261)  评论(0编辑  收藏  举报