Reputation: 225
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?
Upvotes: 3
Views: 9592
Reputation: 7180
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.
Upvotes: 2
Reputation: 36
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.
Upvotes: 1
Reputation: 146
import shutil
shutil.copytree("abc", "copy of abc")
Source: docs.python.org
Upvotes: 2