简体   繁体   English

如何打开文件夹中的第一个文件

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

I am unsure how top open and show the first file in a folder.我不确定 top 如何打开并显示文件夹中的第一个文件。 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:编辑1:

This is the error I now get, isn't this because listdir does indeed return special characters as well?这是我现在得到的错误,这不是因为 listdir 确实也返回特殊字符吗?

在此处输入图片说明

Het whole listdir_nohidden1(path) method should not be necessary for the standard hidden files .标准隐藏文件不需要整个listdir_nohidden1(path)方法. and .. ...

Python method listdir() returns a list containing the names of the entries in the directory given by path. Python 方法 listdir() 返回一个列表,其中包含路径给定的目录中条目的名称。 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'.然而,它不排除其他隐藏文件,如“.DS_store”。

Your problem lies in the fact that os.listdir() only gives the filenames, not the path.您的问题在于os.listdir()只提供文件名,而不是路径。 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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