在文件夹内移动文件夹

Moving folders inside of folders

我有从 00ff 命名的文件夹(全部小写),其中的文件夹数量也是随机命名的。我只需要将里面的文件夹移动到不同的位置。

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")

我希望 D:\folders\(00) 中的所有文件都移入 D:\Mainfolder 并重复,直到所有文件都移入,但出现错误:

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

另外,有什么方法可以改进我制作阵列的方式吗?

您需要将命令修改为: shutil.move(f"D:\folders\{folders[i]}\*","D:\MainFolder")

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 状态:

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

(强调我的)。


作为旁注,您可以更轻松地获取 folders 列表,方法是使用 string formatting:

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

或者干脆避免将这样的列表保存在内存中,只需执行以下操作:

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