-1
import os
import fnmatch
from tempfile import TemporaryFile
#basepath = 'C:\\Uni_Regensburg\\ML_I\\Classification_Algorithm\\Data\\EMG\\'
#with os.scandir(basepath) as entries:
#    for entry in entries:
#        if entry.is_file():
#            print(entry.name)

for dirpath, dirnames, files in os.walk('C:\\University\\ML_I\\Classification_Algorithm\\Data\\EMG'):
    #print(f'found directories: {dirnames}')
    for folder in dirnames:
        #print(folder)
        for file_name in files:
            if fnmatch.fnmatch(file_name, '*.txt'):
                if (folder == 'Aggressive'):
                    print('Aggressive: ' + file_name)

I want to classify my data as binary classification. For this, I have to detect my two folder names: Aggressive and Normal and then I have to filter out only text files. I tried this code, but when I am running this code it returns nothing.

desertnaut
  • 57,590
  • 26
  • 140
  • 166
shivam
  • 249
  • 1
  • 5
  • 18
  • Does this answer your question? [How to use glob() to find files recursively?](https://stackoverflow.com/questions/2186525/how-to-use-glob-to-find-files-recursively) – Chris Mar 30 '20 at 15:54
  • I don't think so, I am searching for folder name and solutions in this question suggesting file name contains a string or file name ending with(fname.endwith) – shivam Mar 30 '20 at 16:08
  • `Path.rglob` allows you to search for partial matches anywhere in the path. So, for example, you could search using a string such as `'**/Agressive/*txt'`. E.g. `aggressive_files = [f for f in Path('.').rglob('**/Aggressive/*.txt')]`. – Chris Mar 30 '20 at 16:56
  • As per https://stackoverflow.com/a/2186565/9576876 – Chris Mar 30 '20 at 17:00

1 Answers1

0

There are some for-loops placed wrong.

def find_folder(path):
    for dirpath, dirnames, files in os.walk(path):
        #print(f'found directories: {dirnames}')
        for folder in dirnames:
            if 'Aggressive' in folder:
                print('Aggressive: ' + path + "\\" + folder)
                return path + "\\" + folder

And then you can get your files as you already did:

def get_files(path_to_folder):
    for dirpath, dirnames, files in os.walk(path_to_folder)
        for file_name in files:
            if fnmatch.fnmatch(file_name, '*.txt'):
                print(file_name)

So in the end you could call it like this

fol = find_folder('C:\\University\\ML_I\\Classification_Algorithm\\Data\\EMG')
get_files(fol)
Banana
  • 2,295
  • 1
  • 8
  • 25