0

I am a python newbie, I have given a task to continuously go in a directory and fetch for a empty sub directory or a files . if the directory is empty it should write the path to a folder.txt , if the directory has files in it should write a path of that file. For example:

Dir a contains:

a/apple/mango/ess.txt
a/gat.xml
a/apple/asl/cdr/opa/est.py
a/apple/dse/
a/dews

Output (folder.txt) file should be :

a/apple/dse/
a/dews

Output (file.txt) file should be :

a/apple/mango/ess.txt
a/gat.xm
a/apple/asl/cdr/opa/est.py

I tried using this logic:

        for subdir, dirs, files in os.walk(path):
            for files in dirs:
                fp1 = (os.path.join(path, files))
                print (fp1)
                if len(os.listdir(fp1)) == 0:
                    print("Directory is empty")
                    folder_added.write("\n Empty folder found %s \n" % (fp1))

but it goes only till two sub folders.

stark
  • 399
  • 2
  • 13
karkator
  • 51
  • 1
  • 10

1 Answers1

0

You're on the right track. Each iteration of this loop describes a new directory. In each directory you want to first check if the list of files is empty. If it is empty, you write the directory path (root, in the example below) to file. If files is not empty, you can loop through it and write the filenames to your other output file:

f_folders = open('folders.txt', 'w')
f_files = open('files.txt', 'w')

for root, dirs, files in os.walk('.'):
    if not files:
        # Empty directory
        f_folders.write(root + '\n')
    else:
        for f in files:
            fpath = os.path.join(root, f)
            f_files.write(fpath + '\n')
Cameron Hyde
  • 118
  • 7