bido whab
bido whab

Reputation: 32

Moving folders inside of folders

I have folders named from 00 to ff (all lower-cased) that have a random number of folders inside them named randomly as well. I need to only move the folders inside to a different location.

folders = list((range(256)))
for i in range(256):
    folders[i] = hex(folders[i])[2:4]
    if len(folders[i]) == 1:
        folders[i] = "0" + folders[i]
for i in range(len(folders)):
    shutil.move(f"D:\folders\{folders[i]\*}", "D:\MainFolder")

I am expecting all the files inside D:\folders\(00) to move into D:\Mainfolder and to repeat until all the files are moved in but it's throwing an error:

OSError: [Errno 22] Invalid argument: 'D:\\folders\\00\\*'

Also, was there any way to improve the way I made the array?

Upvotes: 0

Views: 60

Answers (2)

Tomerikoo
Tomerikoo

Reputation: 19430

shutil.move is expecting to get an explicit path as an argument. It seems that you are confusing with glob that can take the path with shell-like wildcards. I am assuming that with the * you mean to move anything under that folder, but that is not necessary. As the docs state:

Recursively move a file or directory (src) to another location (dst)

(emphasis mine).


As a side note, you can obtain the folders list much easier, by using string formatting:

folders = [f"{hex(i)[2:]:0>2}" for i in range(256)]

Or simply avoid saving such a list in memory and just do:

for i in range(256):
    shutil.move(f"D:\folders\{hex(i)[2:]:0>2}", "D:\MainFolder")

Upvotes: 1

Jean-Marc Volle
Jean-Marc Volle

Reputation: 3333

You need to fix your command as: shutil.move(f"D:\folders\{folders[i]}\*","D:\MainFolder")

Upvotes: 1

Related Questions