Python - Os.walk 遍历不同驱动器中的目录列表

Python - Os.walk loop through list of directories in different drives

我是 Python 初学者,正在寻求有关使用 os.walk 搜索目录列表的帮助。

我的想法是从 SQL 数据库中提取目录列表,这些目录可能具有不同的驱动器号甚至 UNC 路径。我需要做的是搜索这些目录以找到具有特定名称的文件并将其删除。由于该文件可能位于任何目录中,因此需要搜索所有目录。目录列表是不确定的,所以我的想法是将它们存储到一个列表中,然后 os.walk 查看该列表中的所有目录。

def get_location():
    c.execute('SELECT ADDRESS FROM DIRECTORY')
    data = c.fetchall()
    SQLlist = [row for row in data]
    return SQLlist


addresslist = get_location()


def FileDeleter():
    for root, dirs, files in chain.from_iterable(os.walk(addresslist[0:], topdown=False) for path in (str(addresslist[0:]))):
        for file in files:
            if correctID in file:
                if file.endswith('.custextn'):
                    os.remove(os.path.join(root, file))

代码目前是这样的,但我以前试过:

    for root, dirs, files in os.walk(addresslist[0:], topdown=False):

    for root, dirs, files in chain.from_iterable(os.walk(addresslist[0:], topdown=False)):

似乎 os.walk 不接受列表(/元组)。如果我设置 addresslist[0] 或 addresslist[1] 它实际上可以工作,但是因为我不知道可能有多少个地址我很遗憾不能只将 X 地址存储为单独的变量并复制函数。

我的代码 运行 时出现的错误是:

'TypeError: expected str, bytes or os.PathLike object, not list'

最后,我用硬编码的地址列表进行了测试,只是为了排除列表是如何从数据库中提取的问题,例如:

addresslist = ['C:\Subfolder1\Subfolder2', 'D:\Subfolder1\Subfolder2']

并且,由于解包错误:

x,y = ['C:\Subfolder1\Subfolder2', 'D:\Subfolder1\Subfolder2']

谢谢

您的第一个 for 循环没有按照您的要求执行。很接近,但不完全是。

for root, dirs, files in chain.from_iterable(os.walk(addresslist[0:], topdown=False) for path in (str(addresslist[0:])))

你的循环目前正在做的是将你的 addresslist 转换成一个字符串。然后,您实际上是在迭代放入 path 变量的字符串中的每个字符。然后你试图链接一系列 os.walk 生成器。但是 os.walk 需要一条路径。您也没有在代码中的其他任何地方使用该 path 变量。

这应该是:

for path in addresslist:
   # it looks like you are worried that not all paths will be strings
   # if that's really a concern, then leave this next line.
   # Otherwise, I think it is safe to delete it
   path = str(path) 
   for root, dirs, files in os.walk(path, topdown=False):

这将从 addresslist(这是您要搜索的路径)中获取每个元素并对它执行 os.walk。我认为您根本不需要在这里使用 chain

如果您想使用 chain(这不是必需的),您可以遵循此 SO post 提供的大纲:os.walk multiple directories at once.

for root, dirs, files in chain.from_iterable(os.walk(str(path)) for path in addresslist):

您还应该做的另一件事是让 addresslist 成为传递给您的函数的参数。

def FileDeleter(addresslist):
   # your function code here
# then you need to actually call the function
addresses = get_locations()
FileDeleter(addresses)

随着代码变得越来越复杂,依赖全局变量会给您带来很多麻烦。

我现在已经开始工作了,想确认我做了什么。

有两个问题。我需要@TheF1rstPancake 和@Michael Butscher 建议的附加 for 循环。

第二个问题是从数据库中提取目录列表。

def get_location():
    c.execute('SELECT ADDRESS FROM DIRECTORY')
    data = c.fetchall()
    SQLlist = [row for row in data]
    return SQLlist

我正在使用上面的方法,但是当你打印(数据)时发现你得到了一个元组的元组或元组列表,它无法循环供 os.walk 使用。结果看起来像

[('C:\Subfolder1\Subfolder2',), ('D:\Subfolder1\Subfolder2',)]

我使用的解决方案如下

def get_location():
    c.execute('SELECT ADDRESS FROM DIRECTORY')
    data = c.fetchall()
    SQLlist = []
    for row in range(len(data)):
        SQLlist.append(data[row][0])
    return SQLlist

这现在给了我列表:

['C:\Subfolder1\Subfolder2', 'D:\Subfolder1\Subfolder2']

When 运行 此列表通过附加的 for 循环 os.walk 现在可以正确搜索所有目录。

感谢大家的帮助,非常感谢!