1

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
 
3
  • Why do you put the whole loop inside of try-except? It's generally a good idea to just surround the part of the code that can fail, in this case shutil.move(). Commented Feb 27, 2022 at 14:40
  • 1
    Your source and target are the same. Are you trying to move all files of type jpg from one place to another? Your loop won't process 10_000 files anyway - it would stop after 9_000 Commented Feb 27, 2022 at 14:40
  • 1
    side note: use of i and j in your code is extremely unclear Commented Feb 27, 2022 at 14:41

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.