使方法使用递归选择文件的位置



我正在尝试创建一个递归方法;该方法的目标是找到可能包含该文件的最深目录,并确定该文件是否属于此处。如果文件是,我希望它返回完整的文件位置。第一个方法是原来的,但它不适用于return语句。

import zipfile, lxml.etree, os, xml.etree.ElementTree as ET, sys, shutil, re
from docx import Document
path = #Directory where you want files sorted to

原始方法

def findSubDir(file,dire):
tempPath = os.path.join(path,dire.replace(" ",""))
for dirs in os.listdir(tempPath):
if os.path.isdir(os.path.join(tempPath,dirs)):
for names in re.findall('[A-Z][^A-Z]+', dirs):
if names in file:
print(os.path.join(tempPath,dirs))
findSubDir(file,os.path.join(dire,dirs))

修改后的方法

def reFindSubDir(file,dire):
tempPath = os.path.join(path,dire.replace(" ",""))
dirs = [dirs for dirs in os.listdir(tempPath)
if os.path.isdir(os.path.join(tempPath,dirs))]
if(any(os.path.isdir(os.path.join(tempPath,dirs)) for dirs in os.listdir(tempPath))):
print("passed")
folder = "".join([names for dires in dirs for names in re.findall('[A-Z][^A-Z]+', dires)if names in file])
print("folder")
if folder != "":
reFindSubDir(file,os.path.join(dire,folder))
else:
print("Steve2")
return "Steve"
else:
print(tempPath)
return(tempPath)

我在您的代码中立即看到了多个问题。首先,在你最初的尝试中,你似乎错过了一个基本案例。其次,在递归的情况下,不会返回任何内容。

先尝试在不使用regex的情况下使用它,然后可以将其合并到代码中。

def findSubDir(file, dire=""):
tempPath = os.path.join(path, dire)
for dirs in os.listdir(tempPath):
if os.path.isdir(os.path.join(tempPath, dirs)):
return findSubDir(file,os.path.join(tempPath,dirs))
if dirs == file:
return os.path.join(tempPath, file)

最新更新