使用python,选择文件,将excel中名字为"ABCD"和"KKTT"的sheet复制到一个新的excel内并保存在桌面,命名为KKKKT。提高该python代码的运行速度,降低内存不足的问题
时间: 2023-05-17 09:02:29 浏览: 55
以下是Python代码,可以实现将Excel文件中名字为"ABCD"和"KKTT"的sheet复制到一个新的Excel文件中,并将其保存在桌面上,命名为KKKKT:
```python
import pandas as pd
import os
# 读取Excel文件
df = pd.read_excel('input.xlsx', sheet_name=None)
# 选择名字为"ABCD"和"KKTT"的sheet
sheets_to_keep = ['ABCD', 'KKTT']
df = {k: v for k, v in df.items() if k in sheets_to_keep}
# 将选定的sheet保存到新的Excel文件中
writer = pd.ExcelWriter(os.path.expanduser('~/Desktop/KKKKT.xlsx'), engine='xlsxwriter')
for sheet_name, df_sheet in df.items():
df_sheet.to_excel(writer, sheet_name=sheet_name, index=False)
writer.save()
```
为了提高代码的运行速度和降低内存不足的问题,我们可以采取以下措施:
1. 使用Pandas的`read_excel`函数的`sheet_name`参数,只读取需要的sheet,避免读取整个Excel文件。
2. 使用字典推导式,将选定的sheet存储在一个字典中,避免不必要的内存占用。
3. 使用`xlsxwriter`引擎,将选定的sheet保存到新的Excel文件中,避免使用`openpyxl`引擎时出现内存不足的问题。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://img-home.csdnimg.cn/images/20250102104920.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)