简体   繁体   English

为什么 python 在运行时显示文件未找到错误?

[英]why python show file not found error during run time?

I am write a code for collage maker using python and place 2 picture in same folder in which code file exist but when I run a code this error shown: FileNotFoundError: [Errno 2] No such file or directory: 'background.jpg' and my line of code is:我正在使用 python 为拼贴制作者编写代码,并将 2 张图片放在存在代码文件的同一文件夹中,但是当我运行代码时,会显示此错误: FileNotFoundError: [Errno 2] No such file or directory: 'background.jpg'和我的代码行是:

img1 = Image.open("background.jpg")
img2 = Image.open('Awais.jpg')

My Question is how I handle this error?我的问题是我如何处理这个错误?

You would be getting this error because even though you have placed the code and the image in the same directory/folder, the path from where you're running the code matter as that's the working directory for the program.您将收到此错误,因为即使您已将代码和图像放在同一目录/文件夹中,运行代码的路径也很重要,因为它是程序的工作目录。

The best here would be to either use absolute path or make use of os.path.dirname(__file__) and other utilities to fetch the directory where the code file is and use it to reference the image paths.最好的方法是使用绝对路径或使用os.path.dirname(__file__)和其他实用程序来获取代码文件所在的目录并使用它来引用图像路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM