I am trying to read a list of directories from a text file, and use that to copy the directories to a new location. My code below seems to only complete the "#Perform copy or move files" loop for the last item of the list. Can someone please point me in the direction as to why?
import os
import shutil
operation = 'copy' # 'copy' or 'move'
text_file = open('C:\User\Desktop\CopyTrial.txt', "r")
lines = text_file.readlines()
for line in lines:
new_file_name = line[47:]
root_src_dir = os.path.join('.',line)
root_target_dir = os.path.join('.','C:\User\Desktop' + new_file_name)
# Perform copy or move files.
for src_dir, dirs, files in os.walk(root_src_dir):
dst_dir = src_dir.replace(root_src_dir, root_target_dir)
if not os.path.exists(dst_dir):
os.mkdir(dst_dir)
for file_ in files:
src_file = os.path.join(src_dir, file_)
dst_file = os.path.join(dst_dir, file_)
if os.path.exists(dst_file):
os.remove(dst_file)
if operation is 'copy':
shutil.copy(src_file, dst_dir)
elif operation is 'move':
shutil.move(src_file, dst_dir)
text_file.close()
lineinlines?root_src_dirand making sure it contains files to copy.lineinlines. If i printroot_src_dirinside the first for loop it prints the directory for each line, but if i do it inside the second for loop it prints only the directory for the lastlineinlinesos.walk()isn't finding anything to process.