Will
Will

Reputation: 13

Nested for loop only executing for last item of list

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()

Upvotes: 1

Views: 545

Answers (1)

Barmar
Barmar

Reputation: 780673

The lines returned by readlines() include the trailing newlines, but you're not removing this when you create the filename from it. The reason it works for the last line is because your file doesn't end with a newline.

Use rstrip() to remove trailing whitespace.

for line in lines:
    line = line.rstrip()
    ...

Upvotes: 3

Related Questions