标签:写入 读取excel replace listdir writer cat exce insert find
import pandas as pd
import os
import re
path = "./files/"
files = os.listdir(path)
# 用于存放Excel,里面的每个元素类型为:pandas.core.frame.DataFrame
list_excel = []
for filename in files:
fullname = path + filename# excel的相对路径
df = pd.read_excel(fullname)# 默认读取Excel的第一个表单
col_name = df.columns.tolist()
if ‘搜索关键字‘ not in col_name:
# 插入列
index = col_name.index(‘入店来源‘) + 1
col_name.insert(index, ‘搜索关键字‘)
df = df.reindex(columns = col_name)
# 修改值
df.loc[df[‘入店来源‘].str.find(‘手淘搜索‘) > -1 , ‘搜索关键字‘] = df[‘入店来源‘].str.replace(‘手淘搜索‘,‘‘)
df.loc[df[‘入店来源‘].str.find(‘手淘搜索‘) > -1 , ‘入店来源‘] = ‘手淘搜索‘
list_excel.append(df)# 把Excel追加到list中
writer = pd.ExcelWriter(‘test.xlsx‘)
# pd.concat:数据拼接
# to_excel:写入到Excel
pd.concat(list_excel).to_excel(writer,‘sheet1‘,index=False)
writer.save()
print(‘合并完成‘)
标签:写入 读取excel replace listdir writer cat exce insert find
原文地址:https://www.cnblogs.com/guxingy/p/14705682.html