Python 在当前目录以及其子目录下查找文件名包含指定字符串的文件,并打印出相对路径。

论坛 期权论坛 脚本     
匿名网站用户   2020-12-21 09:08   11   0
import os
def search_file(dir,sname): 
    if sname in os.path.split(dir)[1]: #检验文件名里是否包含sname 
        print(os.path.relpath(dir)) #打印相对路径,相对指相对于当前路径 
    if os.path.isfile(dir):   # 如果传入的dir直接是一个文件目录 他就没有子目录,就不用再遍历它的子目录了
        return 

    for dire in os.listdir(dir): # 遍历子目录  这里的dire为当前文件名 
        search_file(os.path.join(dir,dire),sname) #jion一下就变成了当前文件的绝对路径
                                           # 对每个子目录路劲执行同样的操作

其中:

os.path.isfile(path)

    Return True if path is an existing regular file. This follows symbolic links, so both islink() and isfile() can be true for the same path.
os.listdir() 方法用于返回指定的文件夹包含的文件或文件夹的名字的列表。这个列表以字母顺序。 它不包括 '.''..' 即使它在文件夹中。
分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:1136255
帖子:227251
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP