题目:
写一个扫描文件夹的函数scan_files,去扫描imgtest文件夹,将其中的后缀为.jpeg的文件打印出来。
import os
def scan_files(path):
for item in os.listdir(path):
abs_item = os.path.join(path, item)
if os.path.isfile(abs_item):
if abs_item.lower().endswith('.jpeg'):
print(abs_item)
elif os.path.isdir(abs_item):
scan_files(abs_item)
scan_files(r"C:\Users\86151\Desktop\python\imgtest")
解析
导入模块:
import os:导入 Python 的 os 模块,该模块提供了许多与操作系统交互的函数,如文件和目录操作。
定义函数:
def scan_files(path)::定义了一个名为 scan_files 的函数,该函数接受一个参数 path,代表要扫描的目录的路径。
遍历目录:
for item in os.listdir(path)::使用 os.listdir(path) 函数列出 path 目录下的所有文件和目录,将它们存储在 item 变量中,并进行遍历。
abs_item = os.path.join(path, item):使用 os.path.join(path, item) 函数将 path 和 item 组合成一个完整的绝对路径,存储在 abs_item 变量中。
文件判断:
if os.path.isfile(abs_item)::使用 os.path.isfile(abs_item) 函数判断 abs_item 是否为文件。
if abs_item.lower().endswith(‘.jpeg’)::使用 lower() 方法将文件路径转换为小写,然后使用 endswith(‘.jpeg’) 方法判断文件是否以 .jpeg 结尾。如果是,则使用 print(abs_item) 打印文件的完整路径。
目录判断和递归调用:
elif os.path.isdir(abs_item)::使用 os.path.isdir(abs_item) 函数判断 abs_item 是否为目录。
scan_files(abs_item):如果是目录,递归调用 scan_files 函数,继续扫描该目录下的文件和子目录。
调用函数:
scan_files(r"C:\Users\86151\Desktop\python\imgtest"):使用原始字符串 r"C:\Users\86151\Desktop\python\imgtest" 作为路径调用 scan_files 函数,开始扫描操作。
这个函数的主要功能是遍历 imgtest 目录及它的子目录,找出所有以 .jpeg 结尾的文件,并打印它们的完整路径。它通过 os.listdir 函数列出目录下的所有文件和目录,然后使用 os.path.isfile 和 os.path.isdir 函数来区分文件和目录。对于文件,检查后缀是否为 .jpeg;对于目录,递归调用 scan_files 函数,以实现对目录树的深度遍历。