Mir.Emad
Mir.Emad

Reputation: 93

How to separate specific files from sub-folders?

I have 5 folders and inside of them, I have different files and I have to exclude files that start with a specific string. The code that I have written to open directory, sub-folders reading sorting files is below but it is not able to exclude files.

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

Upvotes: 0

Views: 38

Answers (1)

Miller-STGT
Miller-STGT

Reputation: 88

I am kinda confused by this line:

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

Are you trying to find files in the directory which are starting with 'config' and adding them to the list 'CASES'?

Because then the logic is a little bit off. You are creating a full path with os.path.join, then checking if the full path 'C:...' starts with config. And on top of that you store the filename as a sorted list. ['C', ':', ...].

You can could simply say:

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

or

CASES.append(name) if name.startswith('config') else None

Upvotes: 1

Related Questions