侧边栏壁纸
博主头像
意义Meaning

每天过的都要有意义

  • 累计撰写 10 篇文章
  • 累计创建 6 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

python按目录层级输出为excel

意义Meaning
2024-11-12 / 0 评论 / 0 点赞 / 5 阅读 / 0 字
温馨提示:
部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

# encoding=utf-8
import os
import xlwt
from xlwt.Worksheet import Worksheet
import time

path = r'要遍历的文件夹路径'
file_dicts = {}

# 将目录名、文件名读取为字典数据
def find_dir_name(path,key=''):
    file_names = os.listdir(path)
    file_dict = {}
    for file_name in file_names:
        print('当前目录:%s' % path+'\\'+file_name)
        file_dict[file_name] = {}
        if os.path.isdir(path+'\\'+file_name):
            file_dict[file_name] = find_dir_name(path+'\\'+file_name, file_name)
        else:
            pass
    return file_dict




# 将字典数据存入Excel
def edit_excel(worksheet,data):
    # 遍历字典数据
    global row_number, row_data
    for key,value in data.items():
        if value:
            row_data.append(key)
            # 如果value有值,则进行一次遍历
            edit_excel(worksheet,value)
        else:
            # 若value值为空,则将key写入sheet
            # 进行写入excle
            col = 0
            
            for name in row_data:
                print('位置:%d,%d;值:%s' % (row_number,col,name))
                worksheet.write(row_number,col,name)
                col = col+1
                print('位置:%d,%d;值:%s' % (row_number,col,name))
            worksheet.write(row_number,col,key)
            row_number = row_number+1
    if row_data:
        row_data.pop()
    # time.sleep(1)
    return True

if __name__ == '__main__':
    # mm = str(find_dir_name(path,key))
    # f = open('file_name.txt', 'wb')
    # f.write(mm.encode('utf-8'))
    # f.close()
    data = find_dir_name(path)
    # 创建工作表
    workbook = xlwt.Workbook(encoding='utf-8')
    worksheet = workbook.add_sheet('sheet1',cell_overwrite_ok=True)
    # 临时记录一行数据
    row_data = []
    row_number = 0
    edit_excel(worksheet,data)
    workbook.save('输出后的excel文件名称.xls')

0

评论区