3

I have a folder containing several text files. How would I go about using python to make a copy of everyone of those files and put the copies in a new folder?

Randall Ma
  • 10,486
  • 9
  • 37
  • 45
user1558881
  • 225
  • 1
  • 6
  • 14
  • 2
    What have you tried so far? It's easier to help when we know what you have done up to this point. – Levon Jul 28 '12 at 00:44

4 Answers4

2
import shutil
shutil.copytree("abc", "copy of abc")

Source: docs.python.org

Nick Eaket
  • 146
  • 3
2

You can use the glob module to select your .txt files:

import os, shutil, glob

dst = 'path/of/destination/directory'
try:
    os.makedirs(dst) # create destination directory, if needed (similar to mkdir -p)
except OSError:
    # The directory already existed, nothing to do
    pass
for txt_file in glob.iglob('*.txt'):
    shutil.copy2(txt_file, dst)

The glob module only contains 2 functions: glob and iglob (see documentation). They both find all the pathnames matching a specified pattern according to the rules used by the Unix shell, but glob.glob returns a list and glob.iglob returns a generator.

Balthazar Rouberol
  • 6,822
  • 2
  • 35
  • 41
1

I would suggest looking at this post: How do I copy a file in python?

ls_dir = os.listdir(src_path)    
for file in ls_dir:
    copyfile(file, dest_path)

That should do it.

Community
  • 1
  • 1
cloksmith
  • 36
  • 3
  • 1
    `os.system` is discouraged; `subprocess.call` is a recommended alternative: http://docs.python.org/library/subprocess#replacing-os-system – tshepang Jul 28 '12 at 01:05
  • 1
    In this case, neither should be used. Python can read a directory listing just fine (and in a way that handles whitespace in filenames). `os.listdir()` – jordanm Jul 28 '12 at 02:06
  • Thank you for the feedback @Tshepang and jordanm. I updated my suggested answer accordingly. – cloksmith Jul 29 '12 at 05:34
  • Unless you will need `ls_dir` again, you can shorten this to `for file in os.listdir(src_path)`. I would also rather you avoid using a word like `file` for an arbitrary variable, since `file()` is a built-in function. – tshepang Jul 29 '12 at 07:39
0

Use shutil.copyfile

import shutil
shutil.copyfile(src, dst)
sizzzzlerz
  • 4,277
  • 3
  • 27
  • 35