Koloktos
Koloktos

Reputation: 123

Finding all subfolders that contain two files that end with certain strings

So I have a folder, say D:\Tree, that contains only subfolders (names may contain spaces). These subfolders contain a few files - and they may contain files of the form "D:\Tree\SubfolderName\SubfolderName_One.txt" and "D:\Tree\SubfolderName\SubfolderName_Two.txt" (in other words, the subfolder may contain both of them, one, or neither). I need to find every occurence where a subfolder contains both of these files, and send their absolute paths to a text file (in a format explained in the following example). Consider these three subfolders in D:\Tree:

D:\Tree\Grass contains Grass_One.txt and Grass_Two.txt
D:\Tree\Leaf contains Leaf_One.txt
D:\Tree\Branch contains Branch_One.txt and Branch_Two.txt

Given this structure and the problem mentioned above, I'd to like to be able to write the following lines in myfile.txt:

D:\Tree\Grass\Grass_One.txt D:\Tree\Grass\Grass_Two.txt
D:\Tree\Branch\Branch_One.txt D:\Tree\Branch\Branch_Two.txt

How might this be done? Thanks in advance for any help!

Note: It is very important that "file_One.txt" comes before "file_Two.txt" in myfile.txt

Upvotes: 2

Views: 446

Answers (2)

Anonta
Anonta

Reputation: 2540

Here is a recursive solution

def findFiles(writable, current_path, ending1, ending2):
    '''
    :param writable:    file to write output to
    :param current_path: current path of recursive traversal of sub folders
    :param postfix:     the postfix which needs to match before
    :return: None
    '''

    # check if current path is a folder or not
    try:
        flist = os.listdir(current_path)
    except NotADirectoryError:
        return


    # stores files which match given endings
    ending1_files = []
    ending2_files = []


    for dirname  in flist:
        if dirname.endswith(ending1):
            ending1_files.append(dirname)
        elif dirname.endswith(ending2):
            ending2_files.append(dirname)

        findFiles(writable, current_path+ '/' + dirname, ending1, ending2)

    # see if exactly 2 files have matching the endings
    if len(ending1_files)  == 1 and len(ending2_files) == 1:
        writable.write(current_path+ '/'+ ending1_files[0] + ' ')
        writable.write(current_path + '/'+ ending2_files[0] + '\n')


findFiles(sys.stdout, 'G:/testf', 'one.txt', 'two.txt')

Upvotes: 1

Sachin Patel
Sachin Patel

Reputation: 499

import os

folderPath = r'Your Folder Path'

for (dirPath, allDirNames, allFileNames) in os.walk(folderPath):
    for fileName in allFileNames: 
        if fileName.endswith("One.txt") or fileName.endswith("Two.txt") :
            print (os.path.join(dirPath, fileName)) 
            # Or do your task as writing in file as per your need

Hope this helps....

Upvotes: 2

Related Questions