Home > Blockchain >  Python Moving file, if it does not exist go to the next one
Python Moving file, if it does not exist go to the next one

Time:08-03

I would like tot edit this so if the file does not exist goes to the next one. Ive tried pass but it does not work

Here is my script:

MoveTo = r"C:\Users\edward\OneDrive - ISC Industries\Summer Intern 2022\Scripts\Pictures"
with open('PicsWeHave.txt') as my_file:
for filename in my_file:
    MoveFrom = os.path.join(r"C:\Users\edward\OneDrive\Pics")
    shutil.copy(os.path.join(MoveFrom, filename.strip()), os.path.join(MoveTo, filename.strip()))

CodePudding user response:

You can use the os.path.exists function for this.

if not os.path.exists(MoveFrom):
    continue

CodePudding user response:

You could check beforehand, or you could try and copy and then check if it failed with the appropriately named FileNotFoundError:

try:
    shutil.copy(..., ...)
except FileNotFoundError:
    pass

CodePudding user response:

Well that's really very easy especially when using Python! But in order to understand what you're trying to accomplish, it would be very usefull to post the structure of the PicsWeHave.txt file. I mean how that file looks like could help alot. Anyway try to use "continue" instead of "pass".

  • Related