Moving files from a text file with python but the script has to keep running even if there is missing files

Issue

So basically I am trying to write a code that will read a text file. The code will then transfer the file to the destination folder if found in the text file. It’s working well but my only problem is that files names from the text file might be missing in the source folder and I would like the script to keep going to the next line even if a file is missing. I’m not sure if what I said is understandable but thanks in advance.

import shutil
import os
dst = r"C:/Users/Louis/Desktop/destination/"

with open('test.txt') as my_file:
    for filename in my_file:
        file_name  = filename.strip()
        src = r'C:/Users/Louis/Desktop/source/'+ file_name    
        shutil.move(src, dst + file_name)

Solution

Or better without try except:

import shutil
import os
dst = r"C:/Users/Louis/Desktop/destination/"

with open('test.txt') as my_file:
    for filename in my_file:
        file_name  = filename.strip()
        src = r'C:/Users/Louis/Desktop/source/'+ file_name   
        if os.path.exists(src):
            shutil.move(src, dst + file_name)

Answered By – U12-Forward

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published