简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM