文件在目录中的什么位置可以找到?

2024-06-16 14:28:48 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我对Python和Pillow的工作还很陌生。我试图加载一个测试图像并显示它,但它告诉我它找不到目录或文件。我把图像放在同一个文件夹的脚本旁边,所以我不知道哪里出了问题

我试着给图像设置一个直接路径(“C:\Users…etc”),但是它给了我一个不同的unicode错误

from PIL import Image;

trophy_img = Image.open('Trophy.jpg');
trophy_img.show();

以下是我收到的错误消息:

Traceback (most recent call last):
  File "Desktop/Scripts/Pillow_Test/PILTest.py", line 3, in <module>
    trophy_img = Image.open('Trophy.jpg');
  File "C:\Users\Tallen\AppData\Local\Programs\Python\Python37-32\lib\site-packages\PIL\Image.py", line 2652, in open
    fp = builtins.open(filename, "rb")
FileNotFoundError: [Errno 2] No such file or directory: 'Trophy.jpg'

Tags: inpy图像imageimgpil错误line
2条回答

要调试这个,您需要知道 你的current working directory是什么:

import os

print(os.getcwd())

可能你更喜欢change directory 在尝试打开()之前的某个地方

a direct path to the image ("C:\Users...etc")

这句话看起来不太对。 考虑使用raw stringr'C:\Users\foo\bar'。 或者,更好的办法是完全避免反扑:'C:/Users/foo/bar'

所以用户martineau帮了我。用r'C:\Users…etc'解决了这个问题。我以前试过运行这个代码,但是我在r后面加了一个空格,结果没有成功。所以谢谢你们帮我

from PIL import Image

trophy_img = Image.open(r'C:\Users\Tallen\Desktop\Scripts\Pillow_Test\Trophy.jpg');
trophy_img.show()

相关问题 更多 >