生成删除电脑上的空目录、空文档、缓垃圾的脚本
时间: 2023-05-11 18:05:58 浏览: 56
你可以使用以下 Python 脚本来删除电脑上的空目录、空文档和缓存垃圾:
```
import os
def remove_empty_dirs(path):
if not os.path.isdir(path):
return
# remove empty subdirectories
files = os.listdir(path)
if len(files):
for f in files:
fullpath = os.path.join(path, f)
if os.path.isdir(fullpath):
remove_empty_dirs(fullpath)
# if folder empty, delete it
files = os.listdir(path)
if len(files) == 0:
print("Removing empty folder:", path)
os.rmdir(path)
def remove_empty_files(path):
if not os.path.isdir(path):
return
# remove empty files
files = os.listdir(path)
if len(files):
for f in files:
fullpath = os.path.join(path, f)
if os.path.isfile(fullpath) and os.path.getsize(fullpath) == 0:
print("Removing empty file:", fullpath)
os.remove(fullpath)
# remove cache files
for root, dirs, files in os.walk(path):
for file in files:
if file.endswith('.pyc') or file.endswith('.pyo') or file.endswith('.log'):
print("Removing cache file:", os.path.join(root, file))
os.remove(os.path.join(root, file))
if __name__ == '__main__':
remove_empty_dirs('.')
remove_empty_files('.')
```
这个脚本会递归地遍历指定目录下的所有子目录和文件,删除空目录、空文件和缓存垃圾。你可以将脚本保存为一个 .py 文件,然后在命令行中运行它,或者在 Python IDE 中运行它。
相关推荐
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)