这清理电脑垃圾文件的代码嘛,得看你是用哪个操作系统了。Windows系统的话,一般可以用系统自带的磁盘清理工具。但是,如果你想手动写个代码来清理,那得用Python脚本,因为Python简单易学,语法也比较清晰。
比如,我以前就写过一个小脚本,用来清理2022年某个城市某个文件夹里超过一个月的文件。代码是这样的:
python import os import time
# 设定文件夹路径 folder_path = 'D:\\2022年某个城市\\某个文件夹'
# 设定清理时间阈值,比如一个月 time_threshold = 30
# 遍历文件夹 for filename in os.listdir(folder_path): file_path = os.path.join(folder_path, filename) # 检查文件是否是文件而不是文件夹 if os.path.isfile(file_path): # 获取文件的最后修改时间 file_age = time.time() - os.path.getmtime(file_path) # 如果文件年龄超过设定的时间阈值,就删除它 if file_age > time_threshold 24 3600: os.remove(file_path) print(f'已删除:{filename}')
当时写这个脚本的时候,我有点懵,因为我不是程序员,但后来我反应过来,其实这个脚本还是挺简单的。当然,你可能得根据你的实际需求来调整文件夹路径和时间阈值。而且,记得备份重要文件,别把我这个偏激的做法弄丢了重要资料。
比如,我以前就写过一个小脚本,用来清理2022年某个城市某个文件夹里超过一个月的文件。代码是这样的:
python import os import time
# 设定文件夹路径 folder_path = 'D:\\2022年某个城市\\某个文件夹'
# 设定清理时间阈值,比如一个月 time_threshold = 30
# 遍历文件夹 for filename in os.listdir(folder_path): file_path = os.path.join(folder_path, filename) # 检查文件是否是文件而不是文件夹 if os.path.isfile(file_path): # 获取文件的最后修改时间 file_age = time.time() - os.path.getmtime(file_path) # 如果文件年龄超过设定的时间阈值,就删除它 if file_age > time_threshold 24 3600: os.remove(file_path) print(f'已删除:{filename}')
当时写这个脚本的时候,我有点懵,因为我不是程序员,但后来我反应过来,其实这个脚本还是挺简单的。当然,你可能得根据你的实际需求来调整文件夹路径和时间阈值。而且,记得备份重要文件,别把我这个偏激的做法弄丢了重要资料。
1. 使用CCleaner 2. 系统自带的磁盘清理工具 3. 清理临时文件:del /f /s /q %temp%\ 4. 删除系统还原点
python import os import shutil
def clean_up_junk_files(directory): """ 清理指定目录下的垃圾文件。 """ # 定义垃圾文件类型 junk_file_extensions = ['.tmp', '.log', '.bak', '.old', '.dmp', '.err', '.tmp'] # 遍历目录 for root, dirs, files in os.walk(directory): for file in files: # 检查文件扩展名是否在垃圾文件列表中 if file.lower().endswith(junk_file_extensions): file_path = os.path.join(root, file) try: # 删除文件 os.remove(file_path) print(f"Deleted: {file_path}") except Exception as e: print(f"Error deleting {file_path}: {e}")
# 使用示例,替换为你的电脑上需要清理垃圾文件的目录 directory_to_clean = 'C:\\path\\to\\your\\directory' clean_up_junk_files(directory_to_clean)
这段代码定义了一个函数 clean_up_junk_files,它接受一个目录路径作为参数,并删除该目录及其子目录下所有扩展名为 .tmp, .log, .bak, .old, .dmp, .err, .tmp 的文件。请确保在运行此代码之前备份重要数据,因为删除文件是不可逆的。替换 directory_to_clean 变量的值为你要清理的目录路径。
def clean_up_junk_files(directory): """ 清理指定目录下的垃圾文件。 """ # 定义垃圾文件类型 junk_file_extensions = ['.tmp', '.log', '.bak', '.old', '.dmp', '.err', '.tmp'] # 遍历目录 for root, dirs, files in os.walk(directory): for file in files: # 检查文件扩展名是否在垃圾文件列表中 if file.lower().endswith(junk_file_extensions): file_path = os.path.join(root, file) try: # 删除文件 os.remove(file_path) print(f"Deleted: {file_path}") except Exception as e: print(f"Error deleting {file_path}: {e}")
# 使用示例,替换为你的电脑上需要清理垃圾文件的目录 directory_to_clean = 'C:\\path\\to\\your\\directory' clean_up_junk_files(directory_to_clean)
这段代码定义了一个函数 clean_up_junk_files,它接受一个目录路径作为参数,并删除该目录及其子目录下所有扩展名为 .tmp, .log, .bak, .old, .dmp, .err, .tmp 的文件。请确保在运行此代码之前备份重要数据,因为删除文件是不可逆的。替换 directory_to_clean 变量的值为你要清理的目录路径。