首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从子文件夹获取文件

从子文件夹获取文件
EN

Stack Overflow用户
提问于 2018-03-25 14:04:35
回答 2查看 235关注 0票数 0

我对蟒蛇很陌生,所以请容忍我。我正在尝试编写一个利用人脸识别的代码,并以此为基础,我需要能够访问子文件夹。

目前,我在查找文件夹“图像”时遇到了问题。在执行代码时,我位于文件夹face-recognition中,需要访问位于下面一个级别的images

- root

--- face-recognition

-- images

代码语言:javascript
复制
def getImagePath():
    currentPath = os.path.dirname(__file__) # Absolute dir the script is in
    filepath = "../images/" # The path where the pictures are uploaded
    fileList = os.listdir(os.path.join(currentPath, filepath))
    return fileList;

执行此代码会出现错误“`FileNotFoundError: error 2”,没有这样的文件或目录:“../映像/”

编辑:在尝试重写代码之后,我看到了实际问题所在:

代码语言:javascript
复制
def getImages():
    currentPath = os.path.dirname(os.path.abspath(__file__)); # Absolute dir the script is in
    filepath = "../images/"; # The path where the pictures are uploaded
    directory = os.listdir(os.path.join(currentPath, filepath));
    images = [ fi for fi in directory if fi.endswith(('.JPG', '.jpg', 'jpeg', '.JPEG')) ];
    return images;

在我的mac上运行这个代码片段,终端没有任何错误。但是在raspberry-pi 3上运行相同的代码,就会抛出错误,并且它不会导致sens。

解决方案:在检查图像文件夹时,我发现我有一个.gitkeep和.gitignore,它忽略了所有文件(甚至.gitkeep),这就是为什么它会抛出一个错误,因为它在克隆raspberry pi上的回购文件时删除了该文件夹。

EN

回答 2

Stack Overflow用户

发布于 2018-03-25 14:10:11

其中有两部分:

1)你走错了方向。../images/上升到一个目录。你只想要images/。对于绝对引用,您需要/face-recognition/images

glob是你在这里的朋友,https://docs.python.org/3/library/glob.html

代码语言:javascript
复制
import glob 
file_list = glob.glob('/face-recognition/images/*.png')

或者任何你需要的分机。

票数 1
EN

Stack Overflow用户

发布于 2018-03-25 15:19:04

代码语言:javascript
复制
C:\root
├───my
│   └───path
│       └───tmp.py
├───image

路径库模块非常方便(Python 3.4+)。上面的目录结构..。

在tmp.py中:

代码语言:javascript
复制
from pathlib import Path
p = Path(__file__).parent

图像目录位于tmp.py父目录的父目录下。

代码语言:javascript
复制
>>> print(p)
C:\root\my\path
>>> print(p.parent.parent)
C:\root
>>> image_path = p.parent.parent / 'image'
>>> for img in image_path.iterdir():
...     print(img)

C:\root\image\empty.gif
C:\root\image\o.gif
C:\root\image\x.gif
>>>
>>> [str(img) for img in image_path.iterdir()]
['C:\\root\\image\\empty.gif', 'C:\\root\\image\\o.gif', 'C:\\root\\image\\x.gif']
>>>
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49476718

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档