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.
JavaScript
x
15
15
1
import shutil
2
import os
3
import time
4
5
source_dir = 'C:/Users/Kip/Desktop/tarace'
6
target_dir = 'C:/Users/Kip/Desktop/tamere'
7
8
file_names = os.listdir(source_dir)
9
10
while True:
11
for file_name in file_names:
12
shutil.move(os.path.join(source_dir, file_name), target_dir)
13
print("OK")
14
time.sleep(2)
15
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.
JavaScript
1
19
19
1
import shutil
2
import os
3
import time
4
5
source_dir = 'C:/Users/Kip/Desktop/tarace'
6
target_dir = 'C:/Users/Kip/Desktop/tamere'
7
8
while True:
9
file_names = os.listdir(source_dir)
10
if(file_names):
11
print("files found moving..")
12
for file_name in file_names:
13
old_path = os.path.join(source_dir, file_name)
14
new_path = os.path.join(target_dir, file_name)
15
shutil.move(old_path, new_path)
16
print("file {0} -> moved to {1}".format(old_path, new_path))
17
time.sleep(2)
18
19