我正在尝试编写一段代码,它将递归地遍历特定目录的子目录,并且只在到达扩展名为“.nii”的文件时停止,将这些文件附加到名为images的列表中,这是一种广度优先搜索的形式。但是,每当我运行这段代码时,我总是收到[Errno 20]不是一个目录:'/Volumes/ARLO/ADNI/.DS_Store'
*/Volumes/ARLO/ADNI是我要遍历的文件夹
*我在Mac上使用Anaconda的Spyder IDE进行此操作,因为这是我使用numpy和nibabel库的唯一方法,这将在以后变得重要
*我已经检查过此文件夹是否只包含其他文件夹而不包含文件
#preprocessing all the MCIc files
import os
#import nibabel as nib
#import numpy as np
def pwd():
cmd = 'pwd'
os.system(cmd)
print(os.getcwd())
#Part 1
os.chdir('/Volumes/ARLO')
images = [] #creating an empty list to store MRI images
os.chdir('/Volumes/ARLO/ADNI')
list_sample = [] #just an empty list for an earlier version of
#the program
#Part 2
#function to recursively iterate through folder of raw MRI
#images and extract them into a list
#breadth first search
def extract(dir):
#dir = dir.replace('.DS_Store', '')
lyst = os.listdir(dir) #DS issue
for item in lyst:
if 'nii' not in item: #if item is not a .nii file, if
#item is another folder
newpath = dir + '/' + item
#os.chdir(newpath) #DS issue
extract(newpath)
else: #if item is the desired file type, append it to
#the list images
images.append(item)
#Part 3
adni = os.getcwd() #big folder I want to traverse
#print(adni) #adni is a string containing the path to the ADNI
#folder w/ all the images
#print(os.listdir(adni)) this also works, prints the actual list
"""adni = adni + '/' + '005_S_0222'
os.chdir(adni)
print(os.listdir(adni))""" #one iteration of the recursion,
#works
extract(adni)
print(images)
在每次迭代中,我希望通过将文件夹名称附加到增长路径中,进一步遍历嵌套文件夹,代码的第3部分就可以工作了,也就是说,我知道一次迭代就可以了。为什么os
在extract()
函数中将“.DS_Store”部分添加到我的目录中?如何更正我的代码,使宽度优先遍历可以工作?如果没有自动化,我就不能包含几百个图像。在
谢谢。在
^{} 文件不是由
os
模块创建的,而是由Finder(或者,我认为,有时是Spotlight)创建的。它们是macOS存储系统中每个目录的视图选项和图标布局的地方。在他们可能一直都在那里。您在查看时没有看到它们的原因是,在Unix(包括macOS)上,以
.
开头的文件“按惯例隐藏”。除非您要求Finder显示隐藏的文件,ls
不会显示它们,除非您传递-a
标志等所以,这就是你的核心问题:
…是错的。文件夹至少包含一个常规文件;
.DS_Store
。在那么,你能做些什么呢?在
您可以为
.DS_Store
添加特殊处理。在但是更好的解决方案可能是通过调用^{} 来检查每个文件是否是一个文件或目录。在
或者,更好的方法是使用^{} 而不是
listdir
,这样可以为条目提供更多的信息,而不仅仅是名称,因此您不需要像isdir
那样进行额外的调用。在或者,最棒的是,抛出这段代码,使用^{} 递归地访问顶层目录下每个目录中的每个文件。在
相关问题 更多 >
编程相关推荐