1

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()
7
  • Do you mean the last line in lines? Commented Oct 25, 2017 at 22:49
  • Try printing root_src_dir and making sure it contains files to copy. Commented Oct 25, 2017 at 22:51
  • 1
    Why do this with Python when you can just do a recursive directory copy from the command prompt? Commented Oct 25, 2017 at 22:51
  • @Barmar yes that is correct, the code only works fully for the last line in lines . If i print root_src_dir inside 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 last line in lines Commented Oct 25, 2017 at 23:06
  • That means that os.walk() isn't finding anything to process. Commented Oct 25, 2017 at 23:10

1 Answer 1

3

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()
    ...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.