在循环中的函数中使用来自不同文件夹的文件?

2024-10-03 23:18:06 发布

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

我有这样一个主文件夹:

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))

Tags: 文件函数in文件夹forfilesfirstsecond
2条回答

不能使用for ... and循环。您可以在一条语句中循环一个iterable,在另一条语句中循环另一个iterable。这仍然无法满足您的需求:

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

你可能想要的是这样的(我假设mainfmainfo基本上是一样的,只是其中一个是空的):

for folder_num in range(len(mainf)):
    appendfunc(mainf[folder_num], mainfo[folder_num])

你还没有说appendfunc应该做什么,所以我把这个留给你。我还假设,根据您访问文件的方式,您可以找出可能需要如何修改对mainf[folder_num]mainfo[folder_num]的调用(例如,您可能需要以某种方式将数字重新注入目录结构(mainf/{}/streets/streets.shp".format(zero_padded(folder_num))

使用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)

相关问题 更多 >