如何从子文件夹中分离特定文件?

问题描述 投票:0回答:1

我有5个文件夹,在其中,我有不同的文件,必须排除以特定字符串开头的文件。我在下面的目录中写的用于打开目录的子文件夹的代码,但是不能排除文件。

yourpath = r'C:\Users\Hasan\Desktop\output\new our scenario\beta 15\test'

import os
import numpy as np
for root, dirs, files in os.walk(yourpath, topdown=False):
    for name in files:
        #print(os.path.join(root, name))
        CASES = [f for f in sorted(os.path.join(root,name)) if f.startswith('config')] #To find the files

        maxnum = np.max([int(os.path.splitext(f)[0].split('_')[1]) for f in CASES]) #Sorting based on numbers

        CASES= ['configuration_%d.out' % i for i in range(maxnum)] #Reading sorted files
     ## Doing My computations
python numpy
1个回答
1
投票

我有点对这行感到困惑:

CASES = [f for f in sorted(os.path.join(root,name)) if f.startswith('config')] #To find the files

您是否要在目录中查找以'config'开头的文件并将其添加到'CASES'列表中?

因为逻辑有些偏离。您正在使用os.path.join创建完整路径,然后检查完​​整路径'C:...'是否以config开头。最重要的是,您将文件名存储为排序列表。 ['C',':',...]。

您可以简单地说:

if name.startswith('config'):
   CASES.append(name)

CASES.append(name) if name.startswith('config') else None
© www.soinside.com 2019 - 2024. All rights reserved.