Discuss / Python / 第二题

第二题

Topic source

猪才怪君

#1 Created at ... [Delete] [Delete and Lock User]
import os

def search(str,allfile,path):                         #传入要搜索的字符串,空的list,绝对路径
    os.chdir(path)                                    #把当前操作目录变为传入的绝对路径
    for one in os.listdir('.'):                       #迭代当前目录的文件和子目录
        onepath=os.path.join(path,one)                #将迭代的文件或者子目录的绝对路径保存到onepath
        if os.path.isfile(onepath):                   #判断迭代到的是不是文件
            (shotname, extension) = os.path.splitext(one)  #分离文件名和扩展名
            if str in shotname:                       #判断文件名中是否含有扩展名
                allfile.append(onepath)               #把文件的绝对路径存入allfile
        elif os.path.isdir(onepath):                  #判断迭代到的是不是目录
            search(str,allfile,onepath)               #递归search函数,对子目录进行遍历
            os.chdir(os.pardir)                       #完成递归后将操作目录重新返回上级目录(既初始目录)

    return allfile                                    #返回list

if __name__ == '__main__':
    s = search('dll',[],os.path.abspath('.'))
    print([i.strip(os.path.abspath('.')) for i in s])  #把绝对路径中的当前操作目录删除,得到相对路径

猪才怪君

#2 Created at ... [Delete] [Delete and Lock User]

os.scandir()这个函数比较高级一点,迭代到的文件或者目录可以直接用x.name获取名称.看前面大佬的回复学到的


  • 1

Reply