Module4 1
Module4 1
MODULE 4
Organizing Files: The shutil Module, Walking a Directory Tree, Compressing Files
with the zipfile Module, Project: Renaming Files with American-Style Dates to
European-Style Dates, Project: Backing Up a Folder into a ZIP File, Debugging:
Debugger.
Textbook 1: Chapters 10, 11
The first shutil.copy() call copies the file at C:\Users\sonia\spam.txt to the folder
C:\Users\sonia\some_folder. The return value is the path of the newly copied file.
The second shutil.copy() call also copies the file at C:\Users\sonia\eggs.txt to the folder
C:\Users\sonia\some_folder but gives the copied file the name eggs2.txt.
While shutil.copy() will copy a single file, shutil.copytree() will copy an entire folder and
every folder and file contained in it.
Calling shutil.copytree(source, destination) will copy the folder at the path source, along
with all of its files and subfolders, to the folder at the path destination.
Example:
Assuming a folder named eggs already exists in the C:\ directory, this shutil.move() calls
says, \bacon.txt into the folder C:\eggs
in C:\eggs, it would have been overwr s easy to overwrite files. The destination
path can also specify a filename.
Example: >>>shutil.move('C:\\bacon.txt','C:\\eggs\\new_bacon.txt')
'C:\\eggs\\new_bacon.txt'
This line says, C:\bacon.txt into the folder C:\eggs, rename that bacon.txt file to
Both of the previous examples worked under the assumption that there was a folder eggs in the
C:\ directory. But if there is no eggs folder, then move() will rename bacon.txt to a file named
eggs.
>>> shutil.move('C:\\bacon.txt', 'C:\\eggs')
'C:\\eggs'
Here, move() t find a folder named eggs in the C:\ directory and so assumes that destination
must be specifying a filename, not a folder. So the bacon.txt text file is renamed to eggs.
Finally, the folders that make up the destination must already exist, or else Python will throw
an exception.
Example: >>> shutil.move('spam.txt', 'c:\\does_not_exist\\eggs\\ham')
Traceback (most recent call last):
--snip
FileNotFoundError: [Errno 2] No such file or directory: 'c:\\does_not_exist\\
eggs\\ham'
Python looks for eggs and ham inside the directory does_not_exist. It t find the
nonexistent directory, so it t move spam.txt to the path we specified.
Any important files ending with .txt, they would have been accidentally, permanently deleted.
Instead, first run the program: with the os.unlink() call is commented, so Python ignores it.
Instead, print the filename of the file that would have been deleted.
Once we are certain the program works as intended, delete the print(filename) line and
uncomment the os.unlink(filename) line. Then run the program again to actually delete the files.
Safe Deletes with the send2trash Module
Python s built-in shutil.rmtree() function irreversibly deletes files and folders, it can be
dangerous to use. A much better way to delete files and folders is with the third party send2trash
module.
Using send2 s regular delete functions, because it will send
folders and files to s trash or recycle bin instead of permanently deleting them.
If a bug in our program deletes som t intend to delete, we can
later restore it from the recycle bin.
Example:
import os
for folderName, subfolders, filenames in os.walk('C:\\delicious'):
print('The current folder is ' + folderName)
for subfolder in subfolders:
print('SUBFOLDER OF ' + folderName + ': ' + subfolder)
for filename in filenames:
print('FILE INSIDE ' + folderName + ': '+ filename)
print(' ')
The os.walk() function is passed a single string value: the path of a folder. os.walk() function
is used in a for loop statement to walk a directory tree, much like how we can use the range()
function to walk over a range of numbers. Unlike range(), the os.walk() function will return
three values on each iteration through the loop:
1. A string of the current name
2. A list of strings of the folders in the current folder
3. A list of strings of the files in the current folder (By current folder, we mean the folder for
the current iteration of the for loop. The current working directory of the program is not
changed by os.walk().)
Since , it returns three values hence make use of three variables with the names foldername,
subfolders, and filenames.
Output:
The current folder is C:\delicious
SUBFOLDER OF C:\delicious: cats
SUBFOLDER OF C:\delicious: walnut
FILE INSIDE C:\delicious: spam.txt
Since os.walk() returns lists of strings for the subfolder and filename variables, we can use these
lists in their own for loops.
Compressing Files with the zipfile Module
ZIP files (with the .zip file extension), which can hold the compressed contents of many other
files.
Compressing a file reduces its size, which is useful when transferring it over the Internet. And
since a ZIP file can also contain mu s a handy way to package
several files into one. This single file, called an archive file, can then be, attached to an email.
Python programs can both create and open (or extract) ZIP files using functions in the zipfile
module. Say we have a ZIP file named example.zip that has the contents shown in Figure.
A ZipFile object has a namelist() method that returns a list of strings for all the files and
folders contained in the ZIP file.
These strings can be passed to the getinfo() ZipFile method to return a ZipInfo object about
that particular file.
ZipInfo objects have their own attributes, such as file_size and compress_size in bytes, which
hold integers of the original file size and compressed file size, respectively.
While a ZipFile object represents an entire archive file, a ZipInfo object holds useful
information about a single file in the archive.
After running this code, the contents of example.zip will be extracted to current working
directory. Optionally, can pass a folder name to extractall() to have it extract the files into a
folder other than the current working directory. If the folder passed to the extractall() method
does not exist, it will be created.For instance, replaced the call with exampleZip.extractall('C:\\
delicious'), the code would extract the files from example.zip into a newly created C:\delicious
folder. The extract() method for ZipFile objects will extract a single file from the ZIP file.
Example:
>>> exampleZip.extract('spam.txt')
'C:\\spam.txt'
>>> exampleZip.extract('spam.txt', 'C:\\some\\new\\folders')
'C:\\some\\new\\folders\\spam.txt'
>>> exampleZip.close()
The string pass to extract() must match one of the strings in the list returned by namelist().
Optionally, can pass a second argument to extract() to extract the file into a folder other than
the current working directory. If this second argument is a folder that doesn t yet exist, Python
will create the folder. The value that extract() returns is the absolute path to which the file was
extracted.
Creating and Adding to ZIP Files
To create compressed ZIP files, must open the ZipFile object in write mode by passing 'w' as
the second argument.
By passing a path to the write() method of a ZipFile object, Python will compress the file at
that path and add it into t s first argument is a string of the
filename to add. The second argument is the compression type parameter, which tells the
computer what algorithm it should use to compress the files.
We can always just set this value to zipfile.ZIP_DEFLATED. (This specifies the deflate
compression algorithm, which works well on all types of data.)
Example:
This code will create a new ZIP file named new.zip that has the compressed contents of
spam.txt. Writing to files in write mode will erase all existing contents of a ZIP file. To add files
to an existing ZIP file, pass 'a' as the second argument to zipfile.ZipFile() to open the ZIP file
in append mode.
CHAPTER 2: DEBUGGING
Our computer will do only what we tell it to do; we
intended it to do. Even professional prog
program has a problem.
going wrong.
2.1 Raising Exceptions
Python raises an exception whenever it tries to execute invalid code.
We have already
statements so that our program can recover from exceptions that we anticipated.
But we can also raise our own exceptions in our code.
ve
the program execution to the
Exceptions are raised with a raise statement.