J. Devez
J. Devez

Reputation: 329

How to move batches of files in Python?

I have a folder with 1092 files. I need to move those files to a new directory in batches of 10 (each new folder will have only 10 files each, so max. of 110 folders).

I tried this code, and now the folders have been created, but I can't find any of original files (???). They are neither in the original and newly created folders...

path = "/home/user/Documents/MSc/Imagens/Dataset"
paths = []

for root, dirs, file in os.walk(path):
    for name in file:
        paths.append(os.path.join(root,name))

start = 0
end = 10

while end <= 1100:
    dest = str(os.mkdir("Dataset_" + str(start) + "_" + str(end)))
    for i in paths[start:end]:
        shutil.move(i, dest)
    start += 10
    end += 10

Any ideas?

Upvotes: 0

Views: 906

Answers (1)

user1251007
user1251007

Reputation: 16711

With your move command, you are moving all 10 files to one single folder - but not into that folder as the filenames are missing. And dest is none, since os.mkdir() doesn't return anything.

You need to append the filename to dest:

dataset_dirname = "Dataset_" + str(start) + "_" + str(end)
os.mkdir(dataset_dirname)
dataset_fullpath = os.path.join(path, dataset_dirname)
for i in paths[start:end]:
    # append filename to dataset_fullpath and move the file
    shutil.move(i, os.path.join(dataset_fullpath , os.path.basename(i)))

Upvotes: 2

Related Questions