如何删除.jpeg文件避免其转化为.REMOVE_ME文件?
问题分析与解决方案
核心问题原因
- 路径转义错误:你的
dir变量使用普通字符串存储Windows路径,其中\U会被Python解析为Unicode转义序列,导致实际路径与预期不符,触发google_images_search库的临时文件机制(生成.REMOVE_ME后缀文件)。 - 文件句柄未释放:使用
PIL.Image.open()处理图片时未显式关闭文件对象,导致文件资源被占用,os.remove()无法直接删除,进而触发异常。 - 文件列表时效性不足:搜索完成后立即获取的文件列表可能包含未完成下载的临时文件,后续删除时文件状态已变化,引发“文件不存在”错误。
分步解决方案
1. 修复路径转义问题
将路径改为原始字符串(前缀加r),避免转义字符解析错误:
dir = r"C:\Users\user\OneDrive\Pictures\Shitpost generator"
2. 显式释放文件句柄
使用with语句处理PIL图片,自动关闭文件对象,避免资源占用:
# Add text with Image.open(image) as img: font_size = ran.randint(25,200) font = ImageFont.truetype("arial.ttf", font_size) I1 = ImageDraw.Draw(img) h = ran.randint(0, (500-font_size)) try: b = ran.randint(0, (500-(font_size*len(query)))) except: b = 0 I1.text((b,h), query, font=font, fill=(ran.randint(0,255), ran.randint(0,255), ran.randint(0,255))) img = img.convert("RGB") img.save(image)
3. 重新获取文件列表再删除
删除操作前重新读取最新文件列表,过滤临时文件并捕获删除异常:
# 删除文件(排除.REMOVE_ME临时文件) os.chdir(dir) current_files = [ os.path.join(dir, f) for f in os.listdir(dir) if os.path.isfile(f) and not f.endswith('.REMOVE_ME') ] for f in current_files: try: os.remove(f) except Exception as e: print(f"删除失败 {f}: {str(e)}")
4. 额外优化:确保下载完成
在搜索后增加短暂延迟,给文件系统足够时间完成文件写入:
import time # Search gis.search(search_params=_search_params, path_to_dir=dir, width=500, height=500) time.sleep(1) # 等待下载完成
修正后关键代码片段
# Variables query = ran.choice(open("All EN Words.txt").readlines()).strip() # 去除换行符,避免文字带换行 gis = GoogleImagesSearch("API key","Secret key") dir = r"C:\Users\user\OneDrive\Pictures\Shitpost generator" _search_params = { 'q': query, 'num': 1, 'fileType': 'jpg', } # Search gis.search(search_params=_search_params, path_to_dir=dir, width=500, height=500) time.sleep(1) # 获取最新文件(过滤临时文件) os.chdir(dir) folder = [ os.path.join(dir, f) for f in os.listdir(dir) if os.path.isfile(f) and not f.endswith('.REMOVE_ME') ] folder.sort(key=lambda x: os.path.getmtime(x)) image = folder[-1] # 处理文字(with语句自动关文件) with Image.open(image) as img: font_size = ran.randint(25,200) font = ImageFont.truetype("arial.ttf", font_size) I1 = ImageDraw.Draw(img) h = ran.randint(0, (500-font_size)) try: b = ran.randint(0, (500-(font_size*len(query)))) except: b = 0 I1.text((b,h), query, font=font, fill=(ran.randint(0,255), ran.randint(0,255), ran.randint(0,255))) img = img.convert("RGB") img.save(image) # 运动模糊处理 img = cv2.imread(image) size = 15 kernel_motion_blur = np.zeros((size, size)) kernel_motion_blur[int((size-1)/2), :] = np.ones(size) kernel_motion_blur = kernel_motion_blur / size output = cv2.filter2D(img, -1, kernel_motion_blur) cv2.imwrite(image, output) time.sleep(0.5) # 删除文件 current_files = [ os.path.join(dir, f) for f in os.listdir(dir) if os.path.isfile(f) and not f.endswith('.REMOVE_ME') ] for f in current_files: try: os.remove(f) except Exception as e: print(f"删除失败 {f}: {str(e)}")
内容的提问来源于stack exchange,提问作者Cassidy Mettraux
相关产品推荐
相关产品推荐

