从列表的文件路径将不会加载python

从列表的文件路径将不会加载python

问题描述:

我可以加载图像,如果我硬编码的路径,但是当我尝试从列表中拿起字符串我不断收到错误消息。不知道我在做什么错。从列表的文件路径将不会加载python

#for i in range(0,len(training_YFT)): 
    #print(training_YFT[i]) 
#image = Image.open("/media/rafael/Data1/train/YFT/img_00004.jpg") 
image = Image.open(training_YFT[0]) 
#image = Image.open(training_YFT[i]).convert("L") 
arr = np.asarray(image) 
plt.imshow(arr, cmap='gray') 
plt.pause(0.01) 
plt.show() 

我贴在我得到的错误消息下面。 ñ

Traceback (most recent call last): 
    File "/home/rafael/anaconda3/lib/python3.5/site-packages/PIL/Image.py", line 2283, in open 
    fp.seek(0) 
AttributeError: 'str' object has no attribute 'seek' 

During handling of the above exception, another exception occurred: 

Traceback (most recent call last): 
    File "fishy.py", line 95, in <module> 
    image = Image.open(training_YFT[0]) 
    File "/home/rafael/anaconda3/lib/python3.5/site-packages/PIL/Image.py", line 2285, in open 
    fp = io.BytesIO(fp.read()) 
AttributeError: 'str' object has no attribute 'read' 
+2

很奇怪。你可以执行一个'dir(training_YFT [0])并显示结果吗? –

+0

感谢发现问题列表中的第一个元素是空的。 –

+0

我用一个空字符串测试了它,并且如预期的那样“没有这样的文件或目录”消息。奇怪(我相信你,因为这些消息指出一个'str'对象已经通过,但是应该试图打开这个文件,而不是去寻找它) –

Traceback (most recent call last): 
    File "/home/rafael/anaconda3/lib/python3.5/site-packages/PIL/Image.py", line 2283, in open 
    fp.seek(0) 
AttributeError: 'str' object has no attribute 'seek' 

所以第一个错误是,你要调用的对象是file对象,但变量实际上是一个字符串对象。

而且str对象没有被调用函数求

所以移动到列表中的问题。

尝试打印出清单,以确保它不是一个str

['path1', 'path2']

,如果它确实是一个列表,它应该返回给你path1

,如果它是一个字符串,它将返回p,这不是你想要的

接下来,它看起来像Image类想要一个文件对象,并且你传递给它一个字符串。虽然很奇怪,但你之前通过了一个字符串,它似乎工作。我的建议是尝试Image.open(open(variable))

AttributeError: 'str' object has no attribute 'read'

我从来没玩过与PIL包,但是,你能做的最好的事情是打印之前和之后函数的变量,确保它们的变量,你” d喜欢通过

print(training_YFT) 
if not type(training_YFT) == list: print('training_YFT IS NOT A LIST, you\'re giving the function '+training_YET[0]+'!') 
image = Image.open(training_YFT[0]) 
print(image) 
arr = np.asarray(image) 
plt.imshow(arr, cmap='gray') 
plt.pause(0.01) 
plt.show() 

另一个建议是确保文件路径的存在。你可以通过导入os.path isfile来做到这一点。例如from os.path import isfile

由于没有足够的信息来准确确定没有所有源代码,因此无法准确告诉您代码出了什么问题。但我希望这能帮助你,并给你一些想法,以便在事情没有奏效的时候尝试。

+0

如果你看看PIL文档,它们似乎表明通过一个字符串或一个文件是好的。 –