12

I want to copy all my JPG files in one directory to a new directory. How can I solve this in Python?I just start to learn Python.

Thanks for your reply.

fakelbst
  • 578
  • 2
  • 6
  • 13
  • Take a look at these questions which are similar to yours and try out one of the solutions- http://stackoverflow.com/questions/123198/how-do-i-copy-a-file-in-python http://stackoverflow.com/questions/2951659/copy-files-in-folder-up-one-directory-in-python http://stackoverflow.com/questions/3397752/copy-multiple-files-in-python – geeky_bat Aug 10 '12 at 13:52

4 Answers4

31

Of course Python offers all the tools you need. To copy files, you can use shutil.copy(). To find all JPEG files in the source directory, you can use glob.iglob().

import glob
import shutil
import os

src_dir = "your/source/dir"
dst_dir = "your/destination/dir"
for jpgfile in glob.iglob(os.path.join(src_dir, "*.jpg")):
    shutil.copy(jpgfile, dst_dir)

Note that this will overwrite all files with matching names in the destination directory.

Jolly Jumper
  • 756
  • 7
  • 11
  • Thanks a lot. It can work success.But it seem doesn't work for the JPG files in child directory.If I want to get all JPG(include the child directory) How can make it? – fakelbst Aug 10 '12 at 14:38
  • @Seventeenager: You would need to use `os.walk()` to walk the whole directory tree – see the example in the documentation. – Jolly Jumper Aug 10 '12 at 14:49
5

Just use the following code

import shutil, os
files = ['file1.txt', 'file2.txt', 'file3.txt']
for f in files:
    shutil.copy(f, 'dest_folder')

N.B.: You're in the current directory. If You have a different directory, then add the path in the files list. i.e:

files = ['/home/bucket/file1.txt', '/etc/bucket/file2.txt', '/var/bucket/file3.txt']
skpaik
  • 360
  • 5
  • 12
4
import shutil 
import os 

for file in os.listdir(path):
    if file.endswith(".jpg"):
       src_dir = "your/source/dir"
       dst_dir = "your/dest/dir"
       shutil.move(src_dir,dst_dir)
Jat
  • 49
  • 1
3
for jpgfile in glob.iglob(os.path.join(src_dir, "*", "*.jpg")):
    shutil.copy(jpgfile, dst_dir) 

You should write "**" before ".jpg" to search child directories. more "" means more subdirectory to search

Sociopath
  • 13,068
  • 19
  • 47
  • 75
Mustafa Çetin
  • 101
  • 1
  • 1