我对蟒蛇很陌生,所以请容忍我。我正在尝试编写一个利用人脸识别的代码,并以此为基础,我需要能够访问子文件夹。
目前,我在查找文件夹“图像”时遇到了问题。在执行代码时,我位于文件夹face-recognition中,需要访问位于下面一个级别的images。
- root
--- face-recognition
-- images
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”,没有这样的文件或目录:“../映像/”
编辑:在尝试重写代码之后,我看到了实际问题所在:
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上的回购文件时删除了该文件夹。
发布于 2018-03-25 14:10:11
其中有两部分:
1)你走错了方向。../images/上升到一个目录。你只想要images/。对于绝对引用,您需要/face-recognition/images
glob是你在这里的朋友,https://docs.python.org/3/library/glob.html
import glob
file_list = glob.glob('/face-recognition/images/*.png')或者任何你需要的分机。
发布于 2018-03-25 15:19:04
C:\root
├───my
│ └───path
│ └───tmp.py
├───image路径库模块非常方便(Python 3.4+)。上面的目录结构..。
在tmp.py中:
from pathlib import Path
p = Path(__file__).parent图像目录位于tmp.py父目录的父目录下。
>>> 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']
>>>https://stackoverflow.com/questions/49476718
复制相似问题