2014-10-20 51 views
2

我必須使用Python顯示來自文件夾的隨機圖像。我試過如何顯示文件夾中的隨機圖片(Python)

import random, os 
random.choice([x for x in os.listdir("path")if os.path.isfile(x)]) 

但它不是爲我工作(它給Windows錯誤:錯誤的目錄語法,即使我只是複製和粘貼)。

這可能是問題所在?

+0

什麼是您的文件夾的名稱?它是'路徑'嗎? – darthbith 2014-10-20 14:17:58

+0

這是你正在使用的確切代碼?您存儲文件夾的目錄是否真的稱爲「路徑」? – burnpanck 2014-10-20 14:18:01

回答

7

您需要指定正確的相對路徑:

random.choice([x for x in os.listdir("path") 
       if os.path.isfile(os.path.join("path", x))]) 

否則,代碼會試圖找到在當前目錄中,而不是"path"目錄(path\image.jpg)的文件(image.jpg)。

UPDATE

正確指定路徑。尤其是逃避反斜槓或使用r'raw string literal'。否則\..被解釋爲轉義序列。

import random, os 
path = r"C:\Users\G\Desktop\scientific-programming-2014-master\scientific-programming-2014-master\homework\assignment_3\cifar-10-python\cifar-10-batches-py" 
random_filename = random.choice([ 
    x for x in os.listdir(path) 
    if os.path.isfile(os.path.join(path, x)) 
]) 
print(random_filename) 
+0

但這就是我所做的,我指定了文件夾的路徑(而不是「路徑」,我把文件夾路徑,當然)。 – theggg 2014-10-21 14:33:11

+0

@theggg,在這個問題的代碼中,你只放入'x'而不是'os.path.join(「path」,x)' – falsetru 2014-10-21 14:34:02

+0

好吧,對不起,我沒有正確閱讀,我會嘗試。 – theggg 2014-10-21 14:51:47