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?
Asked
Active
Viewed 9,562 times
3
-
2What 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 Answers
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
-
`makedirs(dst)` fails if the destination already exists, unlike `mkdir -p` – Matthew Moisen Jan 26 '16 at 01:18
-
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.
-
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
-
1In 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