user1558881
user1558881

Reputation: 225

Copying several files into new folder

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

Answers (4)

Balthazar Rouberol
Balthazar Rouberol

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

cloksmith
cloksmith

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

Nick Eaket
Nick Eaket

Reputation: 146

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

Source: docs.python.org

Upvotes: 2

user206545
user206545

Reputation:

Use shutil.copyfile

import shutil
shutil.copyfile(src, dst)

Upvotes: 0

Related Questions