excel_dir=path excel_paths=[os.path.join(excel_dir,f)for f in os.listdir(excel_dir)if f.endswith('.xlsx')] dfs=[] for excel_path in excel_paths: df=pd.read_excel(excel_path) dfs.append(df) merged_df=pd.concat(dfs) output_path=r"D:\SMT本部出勤匯總\出勤資料.xlsx" merged_df.to_excel(output_path,index=False) #刪除路徑下文件 folder_path=path for filename in os.listdir(folder_path): file_path=os.path.join(folder_path,filename)#文件路徑 if os.path.isfile(file_path):#判斷是否為文件 os.remove(file_path)#刪除文件 添加一個條件,這個運行完畢后才繼續運行下面的程序
时间: 2024-04-08 21:29:22 浏览: 87
要在删除文件后添加一个条件,确保该操作完成后再继续执行其他程序,你可以使用`try-except`块来捕捉可能的异常并输出错误信息。
以下是修改后的代码示例:
```python
import os
excel_dir = "path"
excel_paths = [os.path.join(excel_dir, f) for f in os.listdir(excel_dir) if f.endswith('.xlsx')]
dfs = []
for excel_path in excel_paths:
df = pd.read_excel(excel_path)
dfs.append(df)
merged_df = pd.concat(dfs)
output_path = r"D:\SMT本部出勤匯總\出勤資料.xlsx"
merged_df.to_excel(output_path, index=False)
# 删除路径下的文件
folder_path = "path"
for filename in os.listdir(folder_path):
file_path = os.path.join(folder_path, filename) # 文件路径
try:
if os.path.isfile(file_path): # 判断是否为文件
os.remove(file_path) # 删除文件
except Exception as e:
print(f"删除文件发生错误: {e}")
# 在这里继续执行其他程序
```
请确保将`path`替换为实际的文件夹路径。如果删除文件时发生错误,将会打印错误信息,并继续执行其他程序。
阅读全文
相关推荐
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.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)
path = 'D:/SMT本部出勤' excel_dir = path excel_paths = [os.path.join(excel_dir, f) for f in os.listdir(excel_dir) if f.endswith('.xls')] dfs = [] for excel_path in excel_paths: df = pd.read_excel(excel_path, engine='openpyxl') df = df.replace({'<a href=': '', '
': ''}, regex=True) # 去除超链接标签 dfs.append(df) merged_df = pd.concat(dfs) output_path = r"D:\SMT本部出勤匯總\熱資料.xlsx" merged_df.to_excel(output_path, index=False),zipfile.BadZipFile: File is not a zip file報這個![](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://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://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)