Lesson 32:

Copying and Moving Files and Folders

Programs can be used to automate the movement and management of files and folders.

The shutil, or shell utiltiies module contains many utilities for copying and moving actions.

After moving into /files:


In [4]:
import os 
# Define base directory
defaultpath = os.path.expanduser('~/Dropbox/learn/books/Python/AutomateTheBoringStuffWithPython')

#Change directory to files directory if set in default 
if (os.getcwd() == defaultpath):
       os.chdir('/files')   
else:
    os.chdir(defaultpath + '/files')

import shutil and use copy() to copy a file:


In [24]:
import shutil # import shutil

shutil.copy('bacon.txt', 'newfiles') # Copy file to a new directory

shutil.copy('bacon.txt', 'bacon2.txt') # Copy file to with a new name


Out[24]:
'bacon2.txt'

copytree() can be used to copy entire directories:


In [16]:
shutil.copytree('newfiles', 'newerfiles') # Copy a directory and rename it


Out[16]:
'newerfiles'

move() can move files and also rename them, and copy them to the same directory with a new name.


In [25]:
shutil.move('bacon2.txt', 'bacon3.txt') # Rename file without moving them 

shutil.move('bacon3.txt', 'newfiles/bacon3.txt') # Move and rename file


Out[25]:
'newfiles/bacon3.txt'

Recap

  • The shutil, or shell utilties module, contain tools for managing files.
  • shutil.copy() can copy files to new folders and duplicate them with new names.
  • shutil.copytree() can copy entire directories
  • shutil.move() move or rename a file.