import os标签:level,python,excel,层次结构,ws,folder,root,structure From: https://www.cnblogs.com/sdfgdrg/p/18281324
import openpyxl
from openpyxl.styles import Font
def get_folder_structure(root_folder):
folder_structure = []
for root, dirs, files in os.walk(root_folder):
level = root.replace(root_folder, '').count(os.sep)
indent = ' ' * 4 * level
folder_structure.append((indent + os.path.basename(root), level))
subindent = ' ' * 4 * (level + 1)
for f in files:
folder_structure.append((subindent + f, level + 1))
return folder_structure
def write_to_excel(folder_structure, excel_file):
wb = openpyxl.Workbook()
ws = wb.active
ws.title = 'Folder Structure'
header_font = Font(bold=True)
ws['A1'] = 'Name'
ws['B1'] = 'Level'
ws['A1'].font = header_font
ws['B1'].font = header_font
for row_num, (name, level) in enumerate(folder_structure, start=2):
ws[f'A{row_num}'] = name
ws[f'B{row_num}'] = level
wb.save(excel_file)
if __name__ == "__main__":
root_folder = input("请输入要遍历的文件夹路径:")
excel_file = input("请输入要保存的Excel文件名(包括路径):")
folder_structure = get_folder_structure(root_folder)
write_to_excel(folder_structure, excel_file)
print(f"文件夹结构已保存到 {excel_file}")