使用Python PIL处理图片时文件名异常追加数字1的原因是什么
问题根因
- 核心问题出在
os.path.splitext的使用逻辑和文件保存的后缀处理两个环节:
- 你调用
os.path.splitext(path2 + file)时,拆分得到的filename[0]是「输出路径+原文件名(不含原后缀)」,例如原输入文件为example.jpg时,filename[0]的值为/home/ulkar/Desktop/testing/example,直接在后面追加1后保存,虽然你指定了保存格式为PNG,但PIL不会自动为你补充.png后缀,第一次运行后得到的文件名是无后缀的example1,而非预期的example1.png。 - 多次运行代码时,后续如果遍历到已生成的无后缀文件,
os.path.splitext拆分无后缀文件时会将整个文件名作为filename[0]返回,例如已生成的example1拆分后filename[0]就是/home/ulkar/Desktop/testing/example1,再次追加1保存就得到example11,反复运行就会出现数字不断追加的情况。
修复代码
#!/usr/bin/env python3 from PIL import Image import os path3 = os.path.join(os.getcwd(), 'Downloads/') path2 = '/home/ulkar/Desktop/testing/' if not os.path.exists(path2): os.makedirs(path2) for file in os.listdir(path3): # 仅拆分原文件名的前缀和后缀 name, ext = os.path.splitext(file) # 拼接输出路径时手动补全.png后缀 output_file = os.path.join(path2, f"{name}1.png") imfile = Image.open(os.path.join(path3, file)) imfile.rotate(90).save(output_file, 'PNG')
内容的提问来源于stack exchange,提问作者Ulkar Bakirova
相关产品推荐
相关产品推荐

