分享一个文件整理使用Python小脚本(删除相同文件减小内存占用)
写在前面:
脚本作用:在目标文件夹中筛选出大小相同的文件,并打印在屏幕上,这样可以快速找出相同文件,释放硬盘内存。
前期部署:安装python并做好配置环境变量(基础)
先上代码:
import os
from collections import defaultdict
def get_drives():
"""
获取用户输入的硬盘盘符列表。
"""
drives = input("请输入硬盘盘符(用空格分隔,例如 C: D:):").strip().split()
# 确保盘符格式正确(例如 C: 或 D:)
drives = [drive.upper() + "\\" if not drive.endswith("\\") else drive.upper() for drive in drives]
return drives
def find_files_with_same_size(drives):
"""
筛选出输入的几个硬盘里大小相同的文件。
:param drives: 硬盘盘符列表
:return: 大小相同的文件列表(每组大小相同的文件存储在一个子列表中)
"""
size_to_files = defaultdict(list) # 用于存储文件大小和对应文件的映射
# 遍历所有硬盘
for drive in drives:
if not os.path.exists(drive):
print(f"警告:硬盘 {drive} 不存在,跳过。")
continue
# 遍历硬盘中的所有文件
for root, _, files in os.walk(drive):
for file in files:
file_path = os.path.join(root, file)
try:
file_size = os.path.getsize(file_path) # 获取文件大小
size_to_files[file_size].append(file_path) # 按文件大小分组
except OSError:
# 忽略无法访问的文件
continue
# 筛选出大小相同的文件(至少有两个文件大小相同)
same_size_files = [files for files in size_to_files.values() if len(files) > 1]
return same_size_files
def main():
"""
主函数:输入硬盘并筛选出大小相同的文件。
"""
# 获取用户输入的硬盘盘符
drives = get_drives()
if not drives:
print("未输入有效的硬盘盘符。")
return
# 筛选出大小相同的文件
same_size_files = find_files_with_same_size(drives)
# 显示筛选结果
if same_size_files:
print("大小相同的文件:")
for files in same_size_files:
print(f"以下文件大小相同(大小:{os.path.getsize(files[0])} 字节):")
for file in files:
print(file)
print("-" * 50) # 分隔每组文件
else:
print("未找到大小相同的文件。")
if __name__ == "__main__":
main()
使用教程:
用记事本拷贝上述代码复制入记事本,修改记事本后缀名为.py
用Python的IDLE打开
按键盘F5开始运行
按要求输入要查找的硬盘,回车。