0% found this document useful (0 votes)
6 views19 pages

Module-04 Organizing Files

The document provides an overview of the shutil module in Python, detailing functions for copying, moving, renaming, and deleting files and folders. It also introduces the zipfile module for creating and extracting ZIP files, including methods for reading and writing compressed files. Additionally, it covers safe deletion using the send2trash module and traversing directories with os.walk().
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views19 pages

Module-04 Organizing Files

The document provides an overview of the shutil module in Python, detailing functions for copying, moving, renaming, and deleting files and folders. It also introduces the zipfile module for creating and extracting ZIP files, including methods for reading and writing compressed files. Additionally, it covers safe deletion using the send2trash module and traversing directories with os.walk().
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

MODULE 4- CHAPTER 1- ORGANIZING FILES

1
the shutil module
• The shutil (or shell utilities) module has functions to let you
copy, move, rename, and delete files in your Python programs.
• To use the shutil functions, you will first need to use import
shutil.

2
Copying Files and Folders
• The shutil module provides functions for copying files, as well as entire
folders.
• Calling shutil.copy(source, destination) will copy the file at the
path source to the folder at the path destination.
• If destination is a filename, that filename will be used as the new name
of the copied file.

3
• The first shutil.copy() call copies the file at
C:\Users\Al\spam.txt to the folder C:\Users\Al\some_folder.

• The function returns the path of the newly copied file:


'C:\\Users\\Al\\some_folder\\spam.txt‘

• Second shutil.copy() also copies the file at C:\Users\Al\eggs.txt


to the folder C:\Users\Al\some_folder but gives the copied file
the name eggs2.txt.

4
• shutil.copy() will copy a single file.
• shutil.copytree() will copy an entire folder and every folder and file
contained in it.
• 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.

• The shutil.copytree() call creates a new folder named spam_backup


with the same content as the original spam folder
5
Moving and Renaming Files and Folders
• Calling shutil.move(source, destination) will move the file or folder at the
path source to the path destination and will return a string of the absolute
path of the new location.
• If destination is a folder, the source file gets moved into destination folder and
keeps its current filename.

>>> import shutil


>>> shutil.move('C:\\bacon.txt', 'C:\\eggs')
'C:\\eggs\\bacon.txt'

• Destination path can be a file name.


>>> shutil.move('C:\\bacon.txt', 'C:\\eggs\\new_bacon.txt')
'C:\\eggs\\new_bacon.txt'
6
Permanently Deleting Files and Folders
• To delete a folder and all of its contents, you use the shutil module.
• os.unlink(path) will delete the file at path.

• os.rmdir(path) will delete the folder at path. This folder must be empty of
any files or folders.

• shutil.rmtree(path) will remove the folder at path, and all files and folders
it contains will also be deleted.

>>>import os
for filename in os.listdir():
if filename.endswith('.rxt'):
os.unlink(filename)
7
Safe Deletes with the send2trash Module

• send2trash is much safer than Python’s regular delete


functions, because it will send folders and files to your
computer’s trash or recycle bin instead of permanently deleting
them.

8
Walking a directory tree
Traversing through a directory (folder) and all its subfolders to
perform some operation on files or folders within them

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('')

APPLICATION DEVELOPMENT
USING PYTHON – 18CS55 9
10
Cont...
• You can use os.walk() in a for loop statement to walk a
directory tree,
• os.walk() function will return three values on each iteration
through the loop:
1. A string of the current folder’s 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

11
Compressing files with the zipfile module
• ZIP files (with the .zip file extension), can hold the compressed
contents of many other files.
• Compressing a file reduces its size, which is useful when
transferring it over the Internet.
• Since a ZIP file can also contain multiple files and subfolders, it’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.

12
Reading ZIP Files

• To read the contents of a ZIP file, first you must create a ZipFile
object.

• To create a ZipFile object, call the zipfile.ZipFile() function,


passing it a string of the .zip file’s filename.

• Note that zipfile is the name of the Python module, and


ZipFile() is the name of the function.

13
14
• 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.
• The command at 1 calculates how efficiently example.zip is
compressed by dividing the original file size by the compressed
file size and prints this information using a string formatted
with %s.
15
Extracting from ZIP Files

• The extractall() method for ZipFile objects extracts all the files and
folders from a ZIP file into the current working directory.

>>> import zipfile, os


>>> os.chdir('C:\\') # move to the folder with example.zip
>>> exampleZip = zipfile.ZipFile('example.zip')
>>> exampleZip.extractall()
>>> exampleZip.close()

• After running this code, the contents of example.zip will be


extracted to C:\.
16
• The extract() method for ZipFile objects will extract a single file
from the ZIP file.
• The value that extract() returns is the absolute path to which the file
was extracted.
• Continue the interactive shell example:

>>> exampleZip.extract('spam.txt')
'C:\\spam.txt'
>>> exampleZip.extract('spam.txt', 'C:\\some\\new\\folders')
'C:\\some\\new\\folders\\spam.txt'
>>> exampleZip.close()
17
Creating and Adding to ZIP Files
• To create your own compressed ZIP files, you must open the
ZipFile object in write mode by passing 'w' as second argument.
• When you pass a path to the write() method of a ZipFile object,
Python will compress the file at that path and add it into the ZIP
file.
• The write() method’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
• zipfile.ZIP_DEFLATED.
18
>>> import zipfile
>>> newZip = zipfile.ZipFile('new.zip', 'w')
>>> newZip.write('spam.txt', compress_type=zipfile.ZIP_DEFLATED)
>>> newZip.close()

19

You might also like