How to copy all the files in a directory

Using shutil module: copy files

There are tons of useful module that you can use with Python to make almost everything. th shutil modul is a built-in one: this means you have it with any installation of Python, without having to install anything. In this post we will see how to use it to copy all the files in a directory and make a backup folder in the same one with the copied files.

The code

We need two modules:

and four methods:

How we make the copy

So, let’s recap what we did in the code.

To copy all the files in a folder into a backup folder,we used shutil.copy().

First we make a folder named ‘backup’, if it doesn’t exist yet (in os.listdir()).

Then we take all the files in the folder with next(os.walk(‘.’) and we copy them in the destination file (‘backup’ folder created before).

import shutil
import os

def copyallfiles():
	"create a backup folder, if not exist, and copy all files in there"
	if not "backup" in os.listdir():
		os.makedirs("backup")

	for f in next(os.walk("."))[2]:
			shutil.copy(f, "backup")

copyallfiles()

Utilities