在路径为C:\Users\user\Desktop\2021.5的文件夹下面有2万个rar格式的压缩包,如何用python解压所有压缩包并且删除其中名字中带有autosave或者crashreport的文件,最后进行重新压缩并把文件名命名为原来的压缩包文件名
时间: 2024-02-23 20:59:45 浏览: 24
你可以使用Python的zipfile和os模块来完成这个任务。首先,你需要遍历文件夹中的所有rar文件,并使用zipfile模块解压缩它们。然后,你需要删除文件名中包含"autosave"或"crashreport"的文件。最后,你需要重新压缩文件并将文件名命名为原始压缩包文件名。
这里是一个简单的代码示例:
```python
import os
import zipfile
path = r"C:\Users\user\Desktop\2021.5"
for filename in os.listdir(path):
if filename.endswith(".rar"):
filepath = os.path.join(path, filename)
with zipfile.ZipFile(filepath, "r") as zip_ref:
zip_ref.extractall(path) # 解压缩
# 删除包含"autosave"或"crashreport"的文件
for f in os.listdir(path):
if "autosave" in f or "crashreport" in f:
os.remove(os.path.join(path, f))
# 重新压缩文件并重命名
with zipfile.ZipFile(filepath, "w") as zip_ref:
for f in os.listdir(path):
if f.endswith(".rar"):
zip_ref.write(os.path.join(path, f), f)
# 删除解压后的文件
for f in os.listdir(path):
if not f.endswith(".rar"):
os.remove(os.path.join(path, f))
```
请注意,这只是一个简单的示例,你需要根据你的具体情况进行修改。例如,你可能需要添加一些错误处理逻辑,以防止在处理文件时出现问题。