def zipjie(): import os import pandas as pd # 指定要合并的文件夹路径 folder_path = r"E:\aaaa\aaaa" fields_to_write = ['aaaa', 'aaaa'] # 获取文件夹中所有的 xlsx 文件路径 xlsx_files = [os.path.join(folder_path, f) for f in os.listdir(folder_path) if f.endswith('.xlsx')] # 创建一个空的 DataFrame 用于存储合并后的数据 merged_data = pd.DataFrame() # 循环读取每个 xlsx 文件,将它们合并到 merged_data 中 for xlsx_file in xlsx_files: # 使用 pandas 读取 xlsx 文件 df = pd.read_excel(xlsx_file) # 将读取到的数据追加到 merged_data 中 merged_data = merged_data.append(df, ignore_index=True) # 在 merged_data 中添加新的一列数据 merged_data['new_column'] = 'new_value' # 将合并后的数据写入到新的 xlsx 文件中 merged_data[fields_to_write + ['new_column']].to_excel(r"E:\aaaa\aaaa\merged_file.xlsx", index=False)优化下这个代码,如果数据是无效字符或者非法字符要替换成其他任意字符进行写入
时间: 2024-03-16 08:48:13 浏览: 130
好的,可以尝试如下优化:
```python
import os
import pandas as pd
def zipjie():
folder_path = r"E:\aaaa\aaaa"
fields_to_write = ['aaaa', 'aaaa']
invalid_chars = ['*', '#', '$'] # 需要替换的非法字符列表
replace_char = '_' # 替换非法字符的字符
xlsx_files = [os.path.join(folder_path, f) for f in os.listdir(folder_path) if f.endswith('.xlsx')]
merged_data = pd.DataFrame()
for xlsx_file in xlsx_files:
df = pd.read_excel(xlsx_file, na_filter=False) # 设置 na_filter=False 不过滤无效值
# 替换非法字符
for c in invalid_chars:
df = df.replace(c, replace_char)
merged_data = merged_data.append(df, ignore_index=True)
merged_data['new_column'] = 'new_value'
# 写入替换后的数据
with pd.ExcelWriter(r"E:\aaaa\aaaa\merged_file.xlsx", engine='xlsxwriter', options={'remove_timezone': True}) as writer:
merged_data[fields_to_write + ['new_column']].to_excel(writer, index=False)
```
优化的主要思路是:在读取Excel文件时设置`na_filter=False`不过滤无效值,并在读取完成之后,替换非法字符。对于写入Excel文件,可以使用`xlsxwriter`库来控制写入的时间格式,以防止出现非法字符。
阅读全文
相关推荐

















