0

I have this Python script that moves all files in a specified directory with a specific file extension. But if the files are located in subdirectories, they won't be moved. How do I move those files too?

import os
import shutil

dest = "/home/thee/Videos/"
sourcePath = raw_input("Enter file location: ")
filetype = raw_input("Enter file type (ex: .mp4): ")

source = os.listdir(sourcePath)

print "Moving all " + filetype + " files from " + sourcePath + " to " + dest

for files in source:
    if files.endswith(filetype):
        shutil.move(os.path.join(sourcePath,files), os.path.join(dest,files))
        print sourcePath + files
thee
  • 53
  • 4
  • 1
    Use `os.walk` instead of `os.listdir` – kindall Jun 27 '16 at 19:09
  • Possible duplicate of [Directory listing in Python](http://stackoverflow.com/questions/120656/directory-listing-in-python) – Anmol Singh Jaggi Jun 27 '16 at 19:10
  • @kindall It returns an error if I do that: if files.endswith(filetype): AttributeError: 'tuple' object has no attribute 'endswith' – thee Jun 27 '16 at 20:42
  • Well, you do have to change the rest of your code too... `walk` is not a drop-in replacement for `listdir` obviously, as can be seen by looking at [the documentation](https://docs.python.org/2/library/os.html#os.walk). – kindall Jun 27 '16 at 20:59

0 Answers0