获取对应文件夹和图片名称

古城微笑少年丶 2023-06-19 06:58 49阅读 0赞

运行程序获取文件夹名称(一级目录、二级目录)和文件名

目标 文件结构是三层结构,从中把一级目录、二级目录、文件名获取到
效果如下:

list\_dir

  1. # _*_coding:utf-8
  2. import os
  3. import re
  4. import time
  5. from openpyxl import Workbook
  6. from openpyxl.styles import Font
  7. def get_file(root_path,suffix):
  8. global fileNum
  9. global dirNum
  10. try:
  11. for dir_name in os.listdir(root_path):
  12. exts = suffix.split(' ')
  13. #获取目录或文件的路径
  14. file_path = os.path.join(root_path,dir_name)
  15. #判断路径为文件还是路径
  16. if os.path.isdir(file_path):
  17. #递归获取所有文件和目录的路径
  18. fileNum += 1
  19. # file.write('#'+'\n')
  20. get_file(file_path,suffix)
  21. else:
  22. for ext in exts:
  23. #根据后缀名判断文件类别
  24. if(dir_name.endswith(ext)):
  25. dirNum += 1
  26. this_dirNum = str(len([lists for lists in os.listdir(root_path)]))
  27. fileName_1dir = file_path.split('\\')[-3]
  28. fileName_2dir = file_path.split('\\')[-2]
  29. file.write(fileName_1dir + '\t' + fileName_2dir + '\t' + this_dirNum + '\t'+ dir_name + '\n')
  30. except FileNotFoundError:
  31. print('地址输入错误,请检查地址'.center(20,'-'))
  32. time.sleep(1.2)
  33. def xls(root_path, outfile):
  34. #生成Excel文件
  35. wb = Workbook()
  36. ws = wb.active
  37. ws.title = '文件名'
  38. #设置表头
  39. ws.row_dimensions[1].font = Font(bold=True,size=20)
  40. ws.column_dimensions['A'].width = 85.0
  41. ws.column_dimensions['B'].width = 95.0
  42. ws.column_dimensions['C'].width = 15.0
  43. ws.column_dimensions['D'].width = 30.0
  44. first_row = []
  45. datas = []
  46. with open(outfile,encoding='utf-8') as f:
  47. is_first_row = True
  48. for line in f:
  49. line = line[:-1]
  50. #存储第一行
  51. if is_first_row:
  52. is_first_row = False
  53. first_row = line.split('\t')
  54. continue
  55. #存储第二行至max_row
  56. datas.append(line.split('\t'))
  57. ws.append(first_row)
  58. for data in datas:
  59. ws.append(data)
  60. wb.save(root_path + '\\dir_list.xlsx')
  61. def output(root_path):
  62. print('The total number of files in '+root_path+' is:',fileNum)
  63. print('The total number of directories in '+ '(' + suffix + ')' +' is:',dirNum)
  64. print('文件写入完成'.center(20,'-'))
  65. time.sleep(1.2)
  66. def main():
  67. get_file(root_path,suffix)
  68. file.close()
  69. xls(root_path, outfile)
  70. output(root_path)
  71. if __name__ == "__main__":
  72. root_path = input('请输入图片所在地址:')
  73. suffix = '.jpg'
  74. outfile = root_path + '\\dir_list.txt'
  75. fileNum = 0
  76. dirNum = 0
  77. seq = '一级目录','二级目录','文件数量','文件名'
  78. file = open(outfile,'w',encoding='utf-8')
  79. file.write('\t'.join(seq) + '\n')
  80. main()

发表评论

表情:
评论列表 (有 0 条评论,49人围观)

还没有评论,来说两句吧...

相关阅读