关于python中的 “ FileNotFoundError: [Errno 2] No such file or directory: '……'问题 ”

本文解决了一个在Python编程中常见的问题:当尝试处理位于特定目录下的图片文件时,由于未使用绝对路径而导致的“FileNotFoundError”。通过添加绝对路径,作者成功解决了这一问题,并分享了完整的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天在学python时,在模仿一个为图片加上图标并移动到指定文件夹的程序时遇到“FileNotFoundError: [Errno 2] No such file or directory: '1528712892362.jpg'”这个问题。

讲讲解决方案,因为我要处理的十几张图片是位于 ‘F:\图片’ 这个路径下的,但是读取到具体的某一个文件时忘记使用绝对路径,如果没有为文件加上前面的绝对路径的话,我的理解是默认在程序所在的路径作为当前路径来查找的,所以就会报错说找不到文件。

后来加上代码中的第10行,并在16行中稍作修改就行了。

 1 import os
 2 from PIL import Image
 3 SQUARE_FIT_SIZE=500
 4 LOGO_FILENAME='catlogo.png'
 5 logoIm=Image.open(LOGO_FILENAME)
 6 width1,height1=logoIm.size
 7 logoIm1=logoIm.resize((int(width1/5),int(height1/5)))
 8 logoWidth,logoHeight=logoIm1.size
 9 logoIm=logoIm1
10 root='F:/图片/'
11 os.makedirs('withLogo',exist_ok=True)
12 for filename in os.listdir('F:\图片'):
13     print(filename)
14     if not (filename.endswith('.png') or filename.endswith('.jpg')) or filename==LOGO_FILENAME:
15         continue
16     im=Image.open(root+filename)
17     width,height=im.size
18     print('Resizing %s...'%(filename))
19     im=im.resize((width,height))
20     print('Adding logo to %s...'%(filename)) 
21     im.paste(logoIm,(width-logoWidth,height-logoHeight),logoIm)
22     im.save(os.path.join('withLogo',filename))

 

转载于:https://www.cnblogs.com/Guhongying/p/9787403.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值