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:

  • os
  • shutil

and four methods:

  • shutil.copy, to copy the files
  • os.listdir(), to check if there is a “backup” folder yet
  • os.makedirs() (to create the subfolder “backup” if there isn’t yet
  • os.walk(), to see al the files in the folder (using next to go just in the root folder and not in any subdirectory)

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

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.