获取对应文件夹和图片名称
运行程序获取文件夹名称(一级目录、二级目录)和文件名
目标 文件结构是三层结构,从中把一级目录、二级目录、文件名获取到
效果如下:
# _*_coding:utf-8
import os
import re
import time
from openpyxl import Workbook
from openpyxl.styles import Font
def get_file(root_path,suffix):
global fileNum
global dirNum
try:
for dir_name in os.listdir(root_path):
exts = suffix.split(' ')
#获取目录或文件的路径
file_path = os.path.join(root_path,dir_name)
#判断路径为文件还是路径
if os.path.isdir(file_path):
#递归获取所有文件和目录的路径
fileNum += 1
# file.write('#'+'\n')
get_file(file_path,suffix)
else:
for ext in exts:
#根据后缀名判断文件类别
if(dir_name.endswith(ext)):
dirNum += 1
this_dirNum = str(len([lists for lists in os.listdir(root_path)]))
fileName_1dir = file_path.split('\\')[-3]
fileName_2dir = file_path.split('\\')[-2]
file.write(fileName_1dir + '\t' + fileName_2dir + '\t' + this_dirNum + '\t'+ dir_name + '\n')
except FileNotFoundError:
print('地址输入错误,请检查地址'.center(20,'-'))
time.sleep(1.2)
def xls(root_path, outfile):
#生成Excel文件
wb = Workbook()
ws = wb.active
ws.title = '文件名'
#设置表头
ws.row_dimensions[1].font = Font(bold=True,size=20)
ws.column_dimensions['A'].width = 85.0
ws.column_dimensions['B'].width = 95.0
ws.column_dimensions['C'].width = 15.0
ws.column_dimensions['D'].width = 30.0
first_row = []
datas = []
with open(outfile,encoding='utf-8') as f:
is_first_row = True
for line in f:
line = line[:-1]
#存储第一行
if is_first_row:
is_first_row = False
first_row = line.split('\t')
continue
#存储第二行至max_row
datas.append(line.split('\t'))
ws.append(first_row)
for data in datas:
ws.append(data)
wb.save(root_path + '\\dir_list.xlsx')
def output(root_path):
print('The total number of files in '+root_path+' is:',fileNum)
print('The total number of directories in '+ '(' + suffix + ')' +' is:',dirNum)
print('文件写入完成'.center(20,'-'))
time.sleep(1.2)
def main():
get_file(root_path,suffix)
file.close()
xls(root_path, outfile)
output(root_path)
if __name__ == "__main__":
root_path = input('请输入图片所在地址:')
suffix = '.jpg'
outfile = root_path + '\\dir_list.txt'
fileNum = 0
dirNum = 0
seq = '一级目录','二级目录','文件数量','文件名'
file = open(outfile,'w',encoding='utf-8')
file.write('\t'.join(seq) + '\n')
main()
还没有评论,来说两句吧...