import os
import openpyxl
def find_image_folders(root_folder):
"""返回所有找到的包含图片的文件夹路径"""
image_folders = set()
for root, dirs, files in os.walk(root_folder):
for file in files:
if file.lower().endswith(('.png', '.jpg', '.jpeg')):
image_folders.add(root)
break
# 这里使用了多级排序:首先按照大层级,然后按照次层级,以此类推
return sorted(list(image_folders), key=lambda x: tuple(x.split(os.sep)))
def save_to_excel(folders, output_path):
"""将路径保存到Excel"""
wb = openpyxl.Workbook()
ws = wb.active
for idx, folder in enumerate(folders, 1):
ws.cell(row=idx, column=1).value = folder # 所有路径都保存在A列中
wb.save(output_path)
def main():
root_folder = input("请输入大地址: ")
folders = find_image_folders(root_folder)
output_path = os.path.join(root_folder, "批量操作文件名.xlsx")
if os.path.exists(output_path):
base_name = "批量操作文件名"
counter = 1
while os.path.exists(output_path):
counter += 1
output_path = os.path.join(root_folder, f"{base_name}_{counter}.xlsx")
save_to_excel(folders, output_path)
print(f"地址已保存到: {output_path}")
if __name__ == "__main__":
main()