Python "move a specefied number of certain files"

I am trying to move a specific number of certain files.

for file_names in file_names[:12]:
    if os.path.isfile(file_names):
        if file_names.endswith('.txt'):
            shutil.move(os.path.join(dir_path, file_names), nf)

The original directory could have 0 to 70 something files no sub folders. It is supposed to run through and create a new folder. Then move 12 txt files into that folder, then repeat. The issue comes from the fact. That the array number counts 12 items, including the folders and moves only the txt items in that array. Sorry hopefully using the right terminology.

So, what happens is it creates the first folder and moves 11 txt files. Then the next folder and moves 9 text files and so on.

So how do get it move 12 text files consistently even with new folders being added to the directory?

>Solution :

There are many ways you could get around this. Maybe use glob to search the directory recursively for files ending in ‘.txt’.

Using basic functions, how about filtering the list of files first?

file_names_filtered = [x for x in file_names if os.path.isfile(x) and x.endswith('.txt')]

for file_names in file_names_filtered[:12]:
        shutil.move(os.path.join(dir_path, file_names), nf)

Leave a Reply