Python-遍历⽂件夹,出其中所有的扩展名相同的⽂件任务⽬标:从某⼀⽂件夹中查全部的具有某⼀扩展名的⽂件(如所有的jpg⽂件),输出他们的绝对路径。
相关知识
os.listdir(path):返回指定路径下的⽂件和⽂件夹列表。
file.split('.')[-1]:分割⽂件名,取最后⼀部分,即取⽂件扩展名。
递归函数
在函数内部,可以调⽤其他函数。如果⼀个函数在内部调⽤⾃⾝本⾝,这个函数就是递归函数。
递归函数特性:
必须有⼀个明确的结束条件;
每次进⼊更深⼀层递归时,问题规模相⽐上次递归都应有所减少
相邻两次重复之间有紧密的联系,前⼀次要为后⼀次做准备(通常前⼀次的输出就作为后⼀次的输⼊)。
⽰例:
def aa(l,u):
print('l=',l,'u=',u)
if l>u:
return 0
else:
return l+aa(l+1,u)
print(aa(3,6))
执⾏过程:
aa(3,6)
3 + aa(4,6)
3 +
4 + aa(5,6)
3 +
4 +
5 + aa(6,6)
3 +
4 +
5 + 6
结果:
18
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 29 12:40:28 2021
"""
import os
def search_extra(Path,File):
#获取当前路径下所有⽂件
try:
allFile=os.listdir(Path)
#对于每⼀个⽂件
for eachFile in allFile:
#若⽂件为⼀个⽂件夹
if os.path.isdir(Path+os.sep+eachFile):
#递归查
search_extra(Path+os.sep+eachFile, File)            #如果是需要被查的⽂件扩展名
elif eachFile.split('.')[-1]==File:
#输出路径python怎么读文件夹下的文件夹
print(Path+os.sep+eachFile,eachFile)
except:
#跳过可能⽆访问权限的⽂件夹
pass
#输⼊待查的初始⽬录:
path=input('')
#输⼊需要查的⽬标⽂件扩展名:
file=input('')
#调⽤查函数
search_extra(path, file)

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。