时间:2022-10-16 11:24:36 | 栏目:Python代码 | 点击:次
当我们发现电脑的内存很满,或平时工作中文件夹管理不清晰,导致里面的文件数据很杂乱,查找很不方便,一个一个文件夹去看去找然后删除又很浪费时间!!
代码如下(示例):
# encoding=utf-8 import os import xlwt from xlwt.Worksheet import Worksheet import time path = r'E:\py\python3.7\test' 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')