创建具有相同名称文件在不同文件夹中的位置清单

2024-09-27 21:26:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试为不同文件夹中具有相同名称和格式的多个文件创建路径列表。我尝试使用os.walk执行此操作,代码如下:

import os

list_raster = []

for (path, dirs, files) in os.walk(r"C:\Users\Douglas\Rasters\Testing folder"):
    for file in files:
        if "woody02.tif" in file:
            list_raster.append(files)
            print (list_raster)

然而,这只给了我两件事

  1. 文件名
  2. 每个文件夹中的所有文件名

我只需要在每个文件夹中指定的'woody02.txt'的完整位置

我做错什么了


Tags: in路径文件夹名称列表foros文件名
2条回答

在您发布的示例代码中,您将files附加到列表中,而不仅仅是当前文件,为了获得当前文件的完整路径和文件名,您需要将代码更改为以下内容:

import os

list_raster = []

for (path, dirs, files) in os.walk(r"C:\Users\Douglas\Rasters\Testing folder"):
    for file in files:
        if "woody02.tif" in file:
            # path will hold the current directory path where os.walk
            # is currently looking and file would be the matching
            # woody02.tif
            list_raster.append(os.path.join(path, file))
# wait until all files are found before printing the list
print(list_raster)

完整路径名是os.walk返回的列表中元组的第一项,因此它已经分配给了path变量

更改:

list_raster.append(files)

收件人:

list_raster.append(os.path.join(path, file))

相关问题 更多 >

    热门问题