akash kesavan
akash kesavan

Reputation: 27

Renaming all the files in a folder is renaming the sub folders too

When try to rename the files in a specific folder, the program code renames all the sub folders too. Is there a way to fix it?

        dname = input("\nenter the path\t")
        if os.path.isdir(dname):
            dst = input("\nenter new file name: \t")
            n = 1
            for i in os.listdir(dname):
                if not os.path.isdir(i):
                    mystr = ".txt"
                    src = os.path.join(dname, i)
                    dd = dst + str(n) + mystr
                    dd = os.path.join(dname, dd)
                    os.rename(src, dd)
                    n += 1

Upvotes: 0

Views: 49

Answers (2)

Shubham Vaishnav
Shubham Vaishnav

Reputation: 1720

Yours "isdirectory" (os.path.isdir(i)) check doesn't seem to work.

You can precompile the list of files present in the directory using the below code,

files = (file for file in os.listdir (dname)
           if os.path.isfile ( os.path.join ( dname, file) ))

And then directly iterate over the files, like,

  for i in files:
    mystr = ".txt"
    src = os.path.join(dname, i)
    dd = dst + str(n) + mystr
    dd = os.path.join(dname, dd)
    os.rename(src, dd)
    n += 1

You can also have a look at this answer, which lists all the ways in which you can list files in a given directory.

Link: https://stackoverflow.com/a/14176179/10164003

Thanks

Upvotes: 1

Arpit
Arpit

Reputation: 478

It seems below the line isn't working for you.

os.path.isdir(i)

Try out creating the full path before checking :

os.path.isdir(os.path.join(dname, i)):

Upvotes: 0

Related Questions