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]:
copytree() can be used to copy entire directories:
In [16]:
shutil.copytree('newfiles', 'newerfiles') # Copy a directory and rename it
Out[16]:
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]: