I’m quite new to Python and I don’t understand why this code crashes without doing anything. It basically moves a file from one folder to another with a message and a delay, and so on.
import shutil import os import time source_dir = 'C:/Users/Kip/Desktop/tarace' target_dir = 'C:/Users/Kip/Desktop/tamere' file_names = os.listdir(source_dir) while True: for file_name in file_names: shutil.move(os.path.join(source_dir, file_name), target_dir) print("OK") time.sleep(2)
What did I do wrong?
Advertisement
Answer
This should work, but don’t forget it will override same named files, if you don’t want this you have to check before moving.
import shutil import os import time source_dir = 'C:/Users/Kip/Desktop/tarace' target_dir = 'C:/Users/Kip/Desktop/tamere' while True: file_names = os.listdir(source_dir) if(file_names): print("files found moving..") for file_name in file_names: old_path = os.path.join(source_dir, file_name) new_path = os.path.join(target_dir, file_name) shutil.move(old_path, new_path) print("file {0} -> moved to {1}".format(old_path, new_path)) time.sleep(2)