Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading