簡體   English   中英

如何打開文件夾中的第一個文件

[英]How do I open the first file in a folder

我不確定 top 如何打開並顯示文件夾中的第一個文件。 目前我的代碼如下:

def listdir_nohidden1(path):
    for f in os.listdir(path):
        if not f.startswith('.'):
            yield f

first = sorted(listdir_nohidden1('/Users/harryhat/Desktop/Code/Experimental/dropvibration200fps'))[0]
image_test = cv.imread(first, 0)
cv.imshow('image', image_test)

cv.waitKey(0)
cv.destroyAllWindows()

代碼的第一部分是必要的,因為有一些隱藏文件不能是紅色的,所以為了避免這種情況,我補充說。 當我嘗試運行此代碼時發生錯誤,錯誤附加為圖像。 該文件夾僅包含圖像欄一個隱藏文件。 有誰知道我做錯了什么。 謝謝

在此處輸入圖片說明

編輯1:

這是我現在得到的錯誤,這不是因為 listdir 確實也返回特殊字符嗎?

在此處輸入圖片說明

標准隱藏文件不需要整個listdir_nohidden1(path)方法. ..

Python 方法 listdir() 返回一個列表,其中包含路徑給定的目錄中條目的名稱。 該列表的順序是任意的。 它不包括特殊條目“.” 和 '..' 即使它們存在於目錄中。

然而,它不排除其他隱藏文件,如“.DS_store”。

您的問題在於os.listdir()只提供文件名,而不是路徑。 打開圖像時應該結合路徑和文件名。

def listdir_nohidden1(path):
    for f in os.listdir(path):
        if not f.startswith('.'):
            yield f

pathname = '/Users/harryhat/Desktop/Code/Experimental/dropvibration200fps'
first = sorted(listdir_nohidden1(pathname))[0]
image_test = cv.imread(os.path.join(pathname, first), 0)
cv.imshow('image', image_test)

cv.waitKey(0)
cv.destroyAllWindows()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM