使用md5sum查找删除同目录重复图片时遇删除报错问题
嘿,我来帮你搞定这个删除重复图片时的报错问题!你遇到的rm: cannot remove 'FILENAME': No such file or directory,本质是脚本执行删除时找不到目标文件,大概率是路径、逻辑或者文件名处理的问题,我给你拆解几个常见原因和对应的修复方案:
可能的原因&修复方案
1. 用了相对路径而非完整路径
这是最常见的问题!如果你的代码在遍历目录时只记录了文件名,没把目录路径和文件名拼接起来,当脚本的工作目录和目标文件所在目录不一致时,rm就会在当前目录找文件,自然找不到。
修复办法:
遍历文件时一定要保存完整文件路径,比如在Python里用os.path.join(dir_path, filename),shell脚本里用"$dir_path/$file",确保删除时指向的是准确的文件位置。
2. 重复文件被多次尝试删除
如果你的代码逻辑是把所有重复文件都列出来,包括已经被删掉的那一份(比如一组重复图有3张,删了第一张后,后面再删第二、第三张没问题,但如果逻辑错误把第一张也重复列了,就会报错)。
修复办法:
在执行删除前先检查文件是否存在,避免白忙活:
- Python里用
if os.path.exists(file_path):判断后再删除 - Shell脚本里用
[ -f "$file_path" ] && rm "$file_path"
3. 文件名包含特殊字符
如果图片文件名有空格、引号、&这类特殊符号,直接用rm FILENAME会被shell解析成多个参数,导致找不到正确的文件。
修复办法:
处理文件名时一定要加引号包裹:
- Shell脚本里用
rm "$file_path" - Python的
os.remove()或shutil.remove()会自动处理大部分特殊字符,只要路径是正确的字符串就行。
示例修正代码
我给你写两个常见场景的修正代码参考:
Python版本(修复路径和存在性检查)
import os from hashlib import md5 def find_duplicates(dir_path): file_hashes = {} duplicate_files = [] # 遍历目录下的所有文件 for filename in os.listdir(dir_path): full_path = os.path.join(dir_path, filename) if os.path.isfile(full_path): # 计算文件MD5哈希值(判断重复的核心) with open(full_path, 'rb') as f: hash_val = md5(f.read()).hexdigest() # 记录重复文件的完整路径 if hash_val in file_hashes: duplicate_files.append(full_path) else: file_hashes[hash_val] = full_path return duplicate_files # 遍历目标目录,删除重复文件 target_dirs = ["dir1", "dir2", "dir3"] # 替换成你的目录列表 for dir_name in target_dirs: if os.path.isdir(dir_name): duplicates = find_duplicates(dir_name) for dup_file in duplicates: if os.path.exists(dup_file): os.remove(dup_file) print(f"已删除重复文件: {dup_file}") else: print(f"文件已不存在,跳过: {dup_file}")
Shell脚本版本(修复路径和特殊字符处理)
#!/bin/bash # 替换成你的目标目录列表,或者用 */ 遍历当前所有子目录 target_dirs=("dir1" "dir2" "dir3") for dir in "${target_dirs[@]}"; do # 确保目录存在 if [ ! -d "$dir" ]; then echo "目录不存在,跳过: $dir" continue fi # 计算文件MD5哈希,筛选出重复文件的完整路径 find "$dir" -maxdepth 1 -type f -exec md5sum {} \; | sort | uniq -w32 -d | cut -c34- | while read -r file_path; do # 检查文件存在后删除,用引号包裹路径处理特殊字符 if [ -f "$file_path" ]; then rm "$file_path" echo "已删除重复文件: $file_path" else: echo "文件已不存在,跳过: $file_path" fi done done
内容的提问来源于stack exchange,提问作者user2334436
相关产品推荐
相关产品推荐

