AHFHenry
AHFHenry

Reputation: 11

Going into subfolders (python)

I've written something to remove special characters in Filenames. But it just includes the one folder and not it's subfolders. How can I do this also in subfolders and subsubfolders and so on?

import os
import re

def dir_list2(directory, *args):

    fileList = []
    content = os.listdir(directory)

    for file in content :

        dirfile = os.path.join(directory, file)
        if os.path.isfile(dirfile):
            if len(args) == 0:
                fileList.append(dirfile)
            else:
                if os.path.splitext(dirfile)[1][1:] in args:
                    fileList.append(dirfile)

        print "##################################################"

        print "Old filename:", file

        filename = file
        remove = re.compile("[^.a-zA-z0-9_]")
        output = remove.sub('_', filename)

        newfile = directory + "/" + output
        os.rename(dirfile, newfile)

        print "Corrected filename:", output
        #Removes Special Characters


    return fileList

if __name__ == '__main__':


    fileList = dir_list2('/path/')

Upvotes: 1

Views: 162

Answers (1)

mpcabd
mpcabd

Reputation: 1807

Try using os.walk instead of os.listdir, it allows you to walk through a folder and its files and subfolders and so on.

Edit your code to be like:

content = os.walk(directory)

for dirpath, dirnames, filenames in content:
    for file in filenames:
        dirfile = os.path.join(dirpath, file)

        # The rest of your code

Upvotes: 2

Related Questions