for root, dirs, files in os.walk(file_dir):#os.walk()方法只能传入绝对路径的文件夹名print(root)# 当前目录路径print(dirs)# 文件夹中所有的目录的名字print(files)# 当前路径下所有文件的文件名return files
directory = file_name("director")# 获取文件for i in directory:try:
data = xlrd.open_workbook(f'E:/PycharmProjects/untitled/director/{i}')# 打开xls文件
table = data.sheets()[0]# 打开第一张表# 获取需要信息
info =[.....]# 将数据修改为实际需要的数据
new_info =[]# 提取出的数据在类型上的处理for d in info:if d =="√":
d ="1"if d =="□":
d ="0"if"A"instr(d):
d ="A"ifbool(re.search(r'\d',str(d))):
d =''.join(list(filter(str.isdigit,str(d))))# isdigit() 方法检测字符串是否只由数字组成
new_info.append(d)# 将信息逐一写入for j inrange(len(new_info)):if new_infos[n].isdigit():
new_infos[n]=int(new_infos[n])
sheet.write(directory.index(i)+1, j +1, new_info[j], style)
sheet.write(directory.index(i)+1,0, i, style)# 写入文件名except:pass
4.容错处理
因为excel表格中的数据有时会记录的不同,或者格式有错误,需要加入容错处理
每一个for循环后的变量保持不同,防止相同变量在循环完改变
熟练使用type()、bool()方法
for h inrange(7,17):if table.cell_value(h,6)in["张","人","万元","台/件","种/类"]:if table.cell_value(h,5)=="":
infos.append(0)else:iftype(table.cell_value(h,5))==float:
infos.append(int(table.cell_value(h,5)))else:
infos.append(table.cell_value(h,5))else:iftype(table.cell_value(h,6))==float:
infos.append(int(table.cell_value(h,6)))else:
infos.append(table.cell_value(h,6))