简体   繁体   中英

How do I open the first file in a folder

I am unsure how top open and show the first file in a folder. Currently my code is as follows:

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()

The first part of the code is necessary as there are some hidden files which can'[t be red so to avoid this I added that. When I try to run this code an error occurs, the error is attached as an image. The folder just contains images bar the one hidden file. Does anyone know what i'm doing wrong. Thanks

在此处输入图片说明

Edit 1:

This is the error I now get, isn't this because listdir does indeed return special characters as well?

在此处输入图片说明

Het whole listdir_nohidden1(path) method should not be necessary for the standard hidden files . and .. .

Python method listdir() returns a list containing the names of the entries in the directory given by path. The list is in arbitrary order. It does not include the special entries '.' and '..' even if they are present in the directory.

It does however not excluded other hidden files, like '.DS_store'.

Your problem lies in the fact that os.listdir() only gives the filenames, not the path. You should combine path and filename when opening the image.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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