我正在尝试编写一段代码,该代码将递归地遍历特定目录的子目录,并且仅在到达扩展名为'.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'部分添加到我的目录中?如何纠正我的代码,以便可以进行广度优先遍历?该文件夹包含数百张MRI图像,没有自动化我将无法做到。
谢谢。
答案 0 :(得分:0)
.DS_Store
文件不是由os
模块创建的,而是由Finder(或者,我认为有时是Spotlight)创建的。它们是macOS存储系统上每个目录的视图选项和图标布局之类的地方。
他们可能一直在那里。当您查看时没有看到它们的原因是,以.
开头的文件在Unix(包括macOS)上被“隐藏”。 Finder不会显示它们,除非您要求它显示隐藏文件。除非您通过ls
标志,否则-a
不会显示它们;等
所以,这是您的核心问题:
我已经检查过该文件夹直接包含其他文件夹而不包含文件
...是错误的。文件夹确实包含至少一个常规文件。 .DS_Store
。
那么,您能做什么?
您可以为.DS_Store
添加特殊处理。
但是更好的解决方案可能是通过调用每个文件os.path.isdir
来检查每个文件是否是文件或目录。
或者,甚至更好的是,使用os.scandir
代替listdir
,这为您提供的条目不仅包含名称,还包含更多信息,因此您无需像isdir
那样进行额外的呼叫
或者,最重要的是,只需抛出这段代码并使用os.walk
来递归访问顶级目录下每个目录中的每个文件。