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

2024-06-28 11:23:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我不确定如何打开和显示文件夹中的第一个文件。目前我的代码如下:

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

代码的第一部分是必需的,因为有一些隐藏文件不能是红色的,所以为了避免这种情况,我添加了它。当我尝试运行此代码时,出现了一个错误,错误被附加为图像。文件夹中只包含一个隐藏文件之外的图像。有人知道我做错了什么吗?谢谢

enter image description here

编辑1:

这就是我现在得到的错误,不是因为listdir确实也返回特殊字符吗

enter image description here


Tags: 文件path代码intest图像image文件夹
1条回答
网友
1楼 · 发布于 2024-06-28 11:23:44

对于标准隐藏文件...,不需要使用整listdir_nohidden1(path)方法

Python方法listdir()返回一个列表,其中包含路径给定目录中的条目名称。列表的顺序是任意的它不包括特殊条目“.”和“..”,即使它们存在于目录中。

但是,它不排除其他隐藏文件,如“.DS\u 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()

相关问题 更多 >