比如我需要获取这两个文件中excel含有关键字的行,文件名就是关键字的值
def find_key_return_row():
dir = r'C:\Users\admin\Desktop\input_data\work\分多个文件夹,返回匹配上文件名的单元格所在行'
key_row_list = []
for root,dirs,files in os.walk(dir):
for file in files:
if file.endswith('.xlsx'):
keyword = file.replace('.xlsx','')
exc_tmp = pd.read_excel(os.path.join(root,file))
for index,row in exc_tmp.iterrows():
for cell in row:
if keyword in str(cell): #excel中有空值和数字,专为str防止报错
row['关键字'] = keyword #增加关键字列
key_row_list.append(row)
break #预想的效果是一行中匹配到一个就跳过这一行,不再比对后面的单元格数据
new_df = pd.DataFrame(data=key_row_list)
new_df.drop_duplicates(inplace=True)
new_df.to_excel(r'C:\Users\admin\Desktop\input_data\work\分多个文件夹,返回匹配上文件名的单元格所在行\结果数据.xlsx',index= False)