0

I am new to python and i am trying to write a script that moves .txt files from different sub directories to one new folder.

import os
import shutil

source_directory = os.path.join('mysourcedirectory', 'source')
target_directory = os.path.join('destinationdirectory', 'target')

operation= 'copy'

for src_dir, dirs, files in os.walk(source_directory):
    if file.endswith(".txt"):
        shutil.copy(os.path.join(target_directory, file))
        

Would someone be able to tell me where I am going wrong and how I can modify this? I'd also like to be able to modify these files (remove header, rename files to consecutive numbers). Can this still be done in one script?

  • Shouldn't it be `if files.endswith(".txt"):` instead of `if file.endswith(".txt"):` and the same in `copy` command, i.e., `files` instead of `file`. Or change in the for loop from `files` to `file` – Sheldore Feb 04 '19 at 12:09
  • Possible duplicate of [Moving all files from one directory to another using Python](https://stackoverflow.com/questions/41826868/moving-all-files-from-one-directory-to-another-using-python) – Sheldore Feb 04 '19 at 12:09
  • You can out your if statement in the duplicate's solution – Sheldore Feb 04 '19 at 12:10

0 Answers0