0

I am trying to move some files from source path to destination path. The program works, the files are able to be moved. But when i run it again to use the "if" statement to check if the files exist - it gets skipped over and goes straight to shutil.move(s, destination) again.

source = '/home/jupyter/.fastai/data/mnist_sample/valid/3/'
destination = '/home/jupyter/.fastai/data/mnist_sample/train/3/'

files_to_move = ['50560.png',  '57306.png',  '983.png']

for file in files_to_move:
    s = source + file
    d = destination + file
    print(d)

if s in source:
    print("exist")
    
else:
    print("File is moving")
    shutil.move(s, destination)
    print('Moved:', file)

Ideal output after moving the files and running it again

exist
exist
exist

Output I get as an error

File is moving
Error: Destination path '/home/jupyter/.fastai/data/mnist_sample/train/3/50560.png' already exists
James Z
  • 12,209
  • 10
  • 24
  • 44
James
  • 15
  • 5
  • Your exists check etc. code is not inside the for loop – James Z Sep 03 '21 at 13:16
  • 1
    also it seems that you are checking if `s` is in `source` rather than something like if `os.path.exists(d)` – lorenzori Sep 03 '21 at 13:25
  • The function shutil.move(s, destination) will get some problem when there is exist file there. Move it after check exist. https://stackoverflow.com/questions/31813504/move-and-replace-if-same-file-name-already-exists – Milo Chen Sep 03 '21 at 14:44

0 Answers0