# @Author: BigMoore
# @Time: 2022/3/29 17:59
import importlib
import sys
import csv
import os
import traceback
import xlrd
def Profiles(dir, ids, profiles):
for town_dir in os.listdir(dir):
newDir = os.path.join(dir, town_dir)
if os.path.isfile(newDir):
profiles.append(newDir)
else:
Profiles(newDir, ids, profiles)
return profiles
def Profiles2(dir, ids, profiles):
for town_dir in os.listdir(dir):
if '青城山' in town_dir:
mount_dir = os.path.join(dir, '青城山镇')
for grop in os.listdir(mount_dir):
grop_dir = os.path.join(mount_dir, grop)
for proj_file in os.listdir(grop_dir):
# ids存放项目编号
ids.append(proj_file[0:19])
# C:\Users\Moore\Desktop\已核对附表\青城山镇\1组\510181012005JB99057邱伟等
proj_file_path = os.path.join(grop_dir, proj_file)
profiles.append(proj_file_path)
else:
# 进入下一级、镇或街道的文件夹
newDir = os.path.join(dir, town_dir)
# os.listdir(*)输出所有文件和文件夹
for proj in os.listdir(newDir):
ids.append(proj[0:19])
proj_file_path = os.path.join(newDir, proj)
profiles.append(proj_file_path)
return ids, profiles
def readExcel(path, writer, identifier):
try:
# 连接excel,连接工作簿
# 打开工作表,选定要读的表,(index+1)
# 设置开始读取数据行
# 遍历数据,设置循环结束条件,读入,结束
workbook = xlrd.open_workbook(path)
worksheet = workbook.sheet_by_index(0)
rowNum = 5
# worksheet.nrows:数据有效行
while rowNum < worksheet.nrows:
row_info = worksheet.row_values(rowNum)
# 去掉第一列序号
row_info = row_info[1:]
# 若有一行没有这3项信息的一项,则跳出if判断,执行rowNum++
if not (row_info[0] == '' and row_info[8] == '' and row_info[-1] == ''):
if row_info[0] != '':
# 将编号放到第一列
row_info.insert(0, identifier)
else:
row_info.insert(0, ' ')
writer.writerow(row_info)
rowNum += 1
except Exception:
print('Error ' + path + ' ' + traceback.format_exc())
def xlsProcess(dir, path):
ids = []
profiles = []
# Profiles(dir, ids, profiles)
Profiles2(dir, ids, profiles)
print(len(profiles))
# print(os.listdir(profiles[0]))
print(len(ids))
# 查看所有文件和编号
# for item in profiles:
# print(item)
# for item in ids:
# print(item)
f = open(path, 'w', encoding='utf-8', newline='')
writer = csv.writer(f)
# 1 遍历所有文件
# 2 取对应编号
# 3 显示所有项目所在下的文件,判断'安置房用地'是否在path内
# 4 有的话通过readExcel写入
# 遍历所有项目
for i in range(len(profiles)):
identifier = ids[i]
for proj in os.listdir(profiles[i]):
if "安置房用地" in proj:
path = os.path.join(profiles[i], proj)
print(path)
readExcel(path, writer, identifier)
if __name__ == '__main__':
importlib.reload(sys)
dir = r'C:\Users\Moore\Desktop\已核对附表'
csv_path = r'C:\Users\Moore\Desktop\已核对附表写入文件\安置房总表.csv'
xlsProcess(dir, csv_path)
# print(os.listdir(dir))
# mounDir = os.path.join(dir, '青城山镇')
# print(mounDir)
# print(os.listdir(mounDir))