首页 > 解决方案 > 在一个循环中使用来自不同文件夹的文件?

问题描述

我有一个这样的主文件夹:

mainf/01/streets/streets.shp
mainf/02/streets/streets.shp    #normal files
mainf/03/streets/streets.shp
...

和另一个像这样的主文件夹:

mainfo/01/streets/streets.shp
mainfo/02/streets/streets.shp   #empty files
mainfo/03/streets/streets.shp
...

我想使用一个函数,它将上层文件夹中的第一个普通文件(普通文件)作为第一个参数,并将另一个文件夹中的对应文件(空文件)作为第二个参数。基于 [-3] 级文件夹编号(例如 01、02、03 等)

带有函数的示例:

appendfunc(first_file_from_normal_files,first_file_from_empty_files)

如何在循环中执行此操作?

我的代码:

for i in mainf and j in mainfo:
    appendfunc(i,j) 

更新 正确版本:

first = ["mainf/01/streets/streets.shp", "mainf/02/streets/streets.shp", "mainf/03/streets/streets.shp"]
second = ["mainfo/01/streets/streets.shp", "mainfo/02/streets/streets.shp", "mainfo/03/streets/streets.shp"]

final = [(f,s) for f,s in zip(first,second)]

for i , j in final:
    appendfunc(i,j)

自动将具有完整路径的主文件夹中的所有文件放入列表的替代方法?

first= []
for (dirpath, dirnames, filenames) in walk(mainf):
    first.append(os.path.join(dirpath,dirnames,filenames))
second = []
for (dirpath, dirnames, filenames) in walk(mainfo):
    second.append(os.path.join(dirpath,dirnames,filenames))

标签: pythonloops

解决方案


使用zip

first = ["mainf/01/streets/streets.shp", "mainf/02/streets/streets.shp", "mainf/03/streets/streets.shp"]
second = ["mainf/01/streets/streets.shp", "mainf/02/streets/streets.shp", "mainf/03/streets/streets.shp"]

final = [(f,s) for f,s in zip(first,second)]
print(final)

推荐阅读