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

Catch file not found error and continue running the code in python

I have Ten thousand files in one folder. The file’s names are numerically sorted. I am trying to move the files. Some files are already moved to a new folder. I have written the code to move the files but due to some files already being moved to a new folder, the code stops when the number hits the number of the file which has already been moved. I tried using try and catch the exception but it’s not working. I would like the code to skip this error and continue moving the files.

This is what I have tired

import os, shutil
path = "I:\\"
moveto = "I:\\"
i = 1
j = 1
try:
    while True:
        f = "{0}.{1}".format(i,j)
        filesrc = f + ".jpg"
        src = path+filesrc
        dst = moveto+filesrc
        shutil.move(src,dst)
        j += 1
        if j > 6:
            i += 1
            j = 1
        if i > 1500:
            break
except for OSError as e:
    pass
 

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

>Solution :

You need to use the try-catch block inside the loop, where the operation might fail.

import os, shutil
path = "I:\\"
moveto = "I:\\"
i = 1
j = 1
while True:
    f = "{0}.{1}".format(i,j)
    filesrc = f + ".jpg"
    src = path+filesrc
    dst = moveto+filesrc
    try:
        shutil.move(src,dst)
    except for OSError as e:
        pass
    j += 1
    if j > 6:
        i += 1
        j = 1
    if i > 1500:
        break

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