-1

I want to copy files with a specific file extention from one directory and put in another directory. I tried searching and found code the same as im doing however it doesnt appear to do anything, any help would be great.

import shutil
import os
source = "/tmp/folder1/"
destination = "/tmp/newfolder/"
for files in source:
    if files.endswith(".txt"):
        shutil.move(files,destination)
gcmtb
  • 15
  • 5
  • In addition to this can you have more than one destination, if i want to copy the same files to two different directories? – gcmtb Jun 13 '17 at 12:52

2 Answers2

0

I think the problem is your for-loop. You are actually looping over the string "tmp/folder1/" instead of looping over the the files in the folder. What your for-loop does is going through the string letter by letter (t, m, p etc.).

What you want is looping over a list of files in the source folder. How that works is described here: How do I list all files of a directory?.

Going fro there you can run through the filenames, testing for their extension and moving them just as you showed.

Gegenwind
  • 1,388
  • 1
  • 17
  • 27
  • Thats was exactly what i was getting, thanks for the link, missing the os.listdir, added this to the source and works fine :-) – gcmtb Jun 13 '17 at 12:38
0

Your "for file in source" pick one character after another one from your string "source" (the for doesn't know that source is a path, for him it is just a basic str object).

You have to use os.listdir :

import shutil
import os

source = "source/"
destination = "dest/"
for files in os.listdir(source): #list all files and directories
    if os.path.isfile(os.path.join(source, files)): #is this a file
        if files.endswith(".txt"): 
            shutil.move(os.path.join(source, files),destination) #move the file

os.path.join is used to join a directory and a filename (to have a complete path).

Gaulois94
  • 159
  • 9