How to copy files to a new directory using Python?

PythonServer Side ProgrammingProgramming

The shutil module provides functions for copying files, as well as entire folders. For copying multiple files at once, you'll have to have a list of all files you want to copy and loop over them to copy them.

Calling shutil.copy(source, destination) will copy the file at the path source to the folder at the path destination. (Both source and destination are strings.) If destination is a filename, it will be used as the new name of the copied file. This function returns a string of the path of the copied file. For example,

import shutil, os
files = ['file1.txt', 'file2.txt', 'file3.txt']
os.mkdir('my_new_folder')
for f in files:
    shutil.copy(f, 'my_new_folder')
raja
Published on 26-Dec-2017 07:38:57
Advertisements