0% found this document useful (0 votes)
111 views

Python Progr Module 3 - 6th EC by 21EC643

Python program

Uploaded by

Mani Prince
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
111 views

Python Progr Module 3 - 6th EC by 21EC643

Python program

Uploaded by

Mani Prince
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Dr.

SURESHA V
Python
Programming

MODULE 3
Pattern Matching with
Regular Expressions
&
Reading and Writing Files

Professor
Dept. of E&CE
K.V.G. College of Engineering, Sullia, D.K-574 327
Affiliated to Visvesvaraya Technological University
Belagavi - 590018
Python Programming (21EC643) - Module 3:
Pattern Matching with Regular Expressions & Reading and Writing Files

MODULE 3
Pattern Matching with Regular Expressions & Reading and Writing Files

Learning Outcomes
After reading this Module, the student will be able to:
o Understand the foundational concepts of regular expressions, including literals,
metacharacters, and escape sequences.
o Learn the syntax of more pattern matching with regular expressions.
o Understand the different functions and methods for managing file paths,
including relative and absolute paths.
o Learn how to open files in different modes (read, write, append).
o Read and write data from files using various methods.
o Create and manage file content effectively, including appending data to existing
files.

 Chapter 7: Pattern Matching with Regular Expressions (TB 1: Page 147-162):


o Finding Patterns of Text Without Regular Expressions, Finding Patterns of Text
with Regular Expressions, More Pattern Matching with Regular Expressions, The
findall() Method, Character Classes, Making Your Character Classes, The Caret
and Dollar Sign Characters, The Wildcard Character, Review of Regex Symbols.
 Chapter 8: Reading and Writing Files (Textbook 1: Page 173-185):
o Files and File Paths, The os. path Module, The File Reading/Writing Process,
Saving Variables with the shelve Module, Saving Variables with the pprint.
pformat() Function
 Web links (e-Resources):
1. https://www.w3schools.com/python/
2. https://www.javapoint.org/python-programming-language/

Chapter 7: Pattern Matching with Regular Expressions


 Introduction:
o Searching and extracting are two common operation in data handling.
o A regular expression (regex) is a sequence of characters that define a search
pattern.
o Searching for required patterns and extracting only the lines/words matching
the pattern is a very common task in solving problems programmatically.

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 1


Python Programming (21EC643) - Module 3:
Pattern Matching with Regular Expressions & Reading and Writing Files

7.1 Finding Patterns of Text Without Regular Expressions


o Finding a string without regular expressions is a laborious and time-consuming
process.
o Illustrate with the following example: To find a phone number in a string. we
know the pattern: three numbers, a hyphen, three numbers, a hyphen, and four.
Here’s an example: 415-555-4242.
o Let’s use a function named isPhoneNumber() in the following code to check
whether a string matches this pattern, returning True or False.

 Program Description: The isPhoneNumber() function contains code that performs


multiple checks.
o To see whether the string in text is a valid phone number. If any of these
checks fail, the function returns False.
o First the code checks that the string is exactly 12 characters. Then it checks
that the area code (that is, the first three characters in text) consists of only
numeric characters .
o The rest of the function checks that the string follows the pattern of a phone
number:
o The number must have the first hyphen after the area code.

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 2


Python Programming (21EC643) - Module 3:
Pattern Matching with Regular Expressions & Reading and Writing Files

o Three more numeric characters then another hyphen , and finally four more
numbers .
o If the program execution manages to get past all the checks, it returns True
o Calling isPhoneNumber() with the argument '415-555-4242' will return True.
o Calling isPhoneNumber() with 'Moshi moshi' will return False; the first test
fails because 'Moshi Moshi' is not 12 characters long.
 Program output:

 Limitation of finding patterns of text without regular expressions:


o The above phone number–finding program works, but it uses a lot of code to
do something limited.
o The isPhoneNumber() function is 17 lines but can find only one pattern of
phone numbers.
o What about a phone number formatted like 415.555.4242 or (415) 555-4242?
o What if the phone number had an extension, like 415-555-4242 x99? The
isPhoneNumber() function would fail to validate them.

7.2 Finding Patterns of Text with Regular Expressions***


o A regular expression (regex) is a sequence of characters that define a search
pattern.
o For example, a \d in a regex stands for a digit character: that is, any single
numeral 0 to 9.
o Python uses the regex \d\d\d-\d\d\d-\d\d\d\d to match the same text the
previous isPhoneNumber() function did
o Regular expressions can be much more sophisticated. For example, adding a 3
in curly brackets ({3}) after a pattern is like saying, “Match this pattern three
times.
o So the slightly shorter regex \d{3}-\d{3}-\d{4} also matches the correct
phone number format.

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 3


Python Programming (21EC643) - Module 3:
Pattern Matching with Regular Expressions & Reading and Writing Files

 Steps to Finding Patterns of Text With Regular Expressions:


1. Creating Regex Objects
2. Matching Regex Objects

1. Creating Regex Objects


o All the regex functions in Python are in the re module.
o import re module
o Passing a string value representing your regular expression to re.compile()
o The re.compile() in Python is a powerful tool for regex pattern development.
o re.compile()returns regular expression pattern to Regex pattern object.
o Passing a string value representing your regular expression to re.compile()
returns a Regex pattern object (or simply, a Regex object).
o To create a Regex object that matches the phone number pattern. Example

o Now the phoneNumRegex variable contains a Regex object.

2. Matching Regex Objects:


o A Regex object’s search() method searches the string it is passed for any
matches to the regex.
o The search() method will return None if the regex pattern is not found in the
string.
o If the pattern is found, the search() method returns a Match object.
o Match objects have a group() method that will return the actual matched text
from the searched string.
o For example,

o group() method returns the complete matched subgroup by default or a


tuple of matched subgroups depending on the number of arguments.

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 4


Python Programming (21EC643) - Module 3:
Pattern Matching with Regular Expressions & Reading and Writing Files

 Review of Regular Expression Matching *** : There are several steps to using
regular expressions in Python, each step is fairly simple.
1. Import the regex module with import re.
2. Create a Regex object with the re.compile() function.
3. Pass the string you want to search into the Regex object’s search() method.
This returns a Match object.
4. Call the Match object’s group() method to return a string of the actual
matched text.

7.3 More Pattern Matching with Regular Expressions: Some of the more powerful
pattern-matching capabilities are
1. Grouping with Parentheses
2. Matching Multiple Groups with the Pipe
3. Optional Matching with the Question Mark
4. Matching Zero or More with the Star
5. Matching One or More with the Plus
6. Matching Specific Repetitions with Curly Brackets

1. Grouping with Parentheses():


o The group() match object method to grab the matching text from just one
group.
o Parentheses are used for grouping expressions, defining functions or passing
arguments, and defining tuples.
o A group is a part of a regex pattern enclosed in parentheses.
o Passing 0 or nothing to the group() method will return the entire matched
text. Example:

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 5


Python Programming (21EC643) - Module 3:
Pattern Matching with Regular Expressions & Reading and Writing Files

o To retrieve all the groups at once, use the groups() method

o Since mo.groups() returns a tuple of multiple values, we can use the multiple-
assignment trick to assign each value to a separate variable, as in the previous
areaCode, mainNumber = mo.groups() line.

2. Matching Multiple Groups with the Pipe (|)


o The vertical bar | character is called a pipe
o Use Pipe (|)is used anywhere to match one of many expressions.
o For example, the regular expression r'Batman | Tina Fey' will match either
'Batman' or 'Tina Fey'.
o When both Batman and Tina Fey occur in the searched string, the first
occurrence of matching text will be returned as the Match object.
o Example:

o You can use the pipe symbol "|" to match one of several patterns as part of your
regex. For example, to match any of the strings 'Batman', 'Batmobile', 'Batcopter',
and 'Batbat', you can specify the common prefix 'Bat' only once using ( )

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 6


Python Programming (21EC643) - Module 3:
Pattern Matching with Regular Expressions & Reading and Writing Files

o The method call mo.group() returns the full matched text 'Batmobile', while
mo.group(1) returns just the part of the matched text inside the first parentheses
group, 'mobile'.
o By using the pipe character and grouping parentheses, we can specify several
alternative patterns you would like your regex to match.

3. Optional Matching with the Question Mark (?)


o The ? character flags the group that precedes it as an optional part of the pattern.
o The question mark makes the previous token in the regular expression optional.
o Example:

o The (wo)? part of the regular expression means that the pattern wo is an
optional group.
o The regex will match text that has zero instances or one instance of (wo) in it.
o This is why the regex matches both 'Batwoman' and 'Batman'.

4. Matching Zero or More with the Star (*)


o The * (called the star or asterisk) means “match zero or more”: the group that
precedes the star can occur any number of times in the text. It can be completely
absent or repeated over and over again.
o Example:

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 7


Python Programming (21EC643) - Module 3:
Pattern Matching with Regular Expressions & Reading and Writing Files

o For 'Batman', the (wo)* part of the regex matches zero instances of wo in the
string; for 'Batwoman', the (wo)* matches one instance of (wo); and for
'Batwowowowoman', (wo)* matches FOUR instances of (wo).

5. Matching One or More with the Plus (+)


o The + (or plus) means “match one or more.” The group preceding a plus must
appear at least once. Example

6. Matching Specific Repetitions with Curly Brackets {}


o If you have a group that you want to repeat a specific number of times, follow
o the group in your regex with a number in curly brackets.
o For example, the regex (Ha){3} will match the string 'HaHaHa',
o Instead of one number, specify a range by writing a minimum, a comma, and a
maximum in between the curly brackets.
o For example, the regex (Ha){3,5} will match 'HaHaHa', 'HaHaHaHa', and
'HaHaHaHaHa'.
o Curly brackets can help make your regular expressions shorter. Example

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 8


Python Programming (21EC643) - Module 3:
Pattern Matching with Regular Expressions & Reading and Writing Files

7.4 Greedy and Nongreedy Matching


o Python’s regular expressions are greedy by default.
o For example (Ha){3,5} can match three, four, or five instances of Ha in the string
'HaHaHaHaHa'.
o Match the object’s call to group() in ambiguous situations they will match the
longest string possible.
o The nongreedy version of the curly brackets, which matches the shortest string
possible, has the closing curly bracket followed by a question mark.
o Example:

7.5 The findall() Method


o search() will return a Match object of the first matched text in the searched
string.
o The findall() method will return the strings of every match in the searched string.
o Example:

o findall() will not return a Match object but a list of strings—as long as there are
no groups in the regular expression. Each string in the list is a piece of the
searched text that matched the regular expression.
o Example:

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 9


Python Programming (21EC643) - Module 3:
Pattern Matching with Regular Expressions & Reading and Writing Files

7.6 Character Classes


o In the earlier phone number regex example, we learned that \d could stand for
any numeric digit. That is, \d is shorthand for the regular expression
(0|1|2|3|4|5|6|7|8|9).
o There are many such shorthand character classes, as shown in Table 7-1.

o Character classes are good for shortening regular expressions. The character
class [0-5] will match only the numbers 0 to 5; this is much shorter than typing
(0|1|2|3|4|5).
o The regular expression \d+\s\w+ will match text that has one or more numeric
digits (\d+), followed by a whitespace character (\s), followed by one or more
letter/digit/underscore characters (\w+). The findall() method returns all
matching strings of the regex pattern in a list.

7.7 Making Your Own Character Classes


o We can define your own character class using square brackets.
o For example, the character class [aeiouAEIOU] will match any vowel, both
lowercase and uppercase. Example

o We can also include ranges of letters or numbers by using a hyphen. For


example, the character class [a-zA-Z0-9] will match all lowercase letters,
uppercase letters, and numbers.

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 10


Python Programming (21EC643) - Module 3:
Pattern Matching with Regular Expressions & Reading and Writing Files

7.8 The Caret (^) and Dollar ($) Sign Characters


o Caret symbol (^) at the start of a regex to indicate that a match must occur at the
beginning of the searched text.
o dollar sign ($) at the end of the regex to indicate the string must end with this
regex pattern.
o We can use the ^ and $ together to indicate that the entire string must match the
regex—that is, it’s not enough for a match to be made on some subset of the
string.
o For example, the r'^Hello' regular expression string matches strings that begin
with 'Hello'.

7.9 The Wildcard Character (.)


o The . (or dot) character in a regular expression is called a wildcard and will
match any character except for a new line.
o For example

o Note: The dot character will match just one character, which is why the match for
the text flat in the previous example matched only lat.

7.10 Matching Everything with Dot-Star (.*)


o We can use the dot-star (.*) to stand in for that “anything.”
o Remember that the dot character means “any single character except the
newline,” and the star character means “zero or more of the preceding
character.” Example

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 11


Python Programming (21EC643) - Module 3:
Pattern Matching with Regular Expressions & Reading and Writing Files

o The dot-star (.*) uses greedy mode: It will always try to match as much text as
possible.
o The dot, star, and question mark (.*?): To match any and all text.
o Enter the following into the interactive shell to see the difference between the
greedy and nongreedy versions:

7.11 Matching Newlines with the Dot Character


o The dot-star will match everything except a newline. By passing re.DOTALL as
the second argument to re.compile(), you can make the dot character match all
characters, including the newline character.Example

7.12 Review of Regex Symbols


o The ? matches zero or one of the preceding group.
o The * matches zero or more of the preceding group.
o The + matches one or more of the preceding group.
o The {n} matches exactly n of the preceding group.
o The {n,} matches n or more of the preceding group.
o The {,m} matches 0 to m of the preceding group.
o The {n,m} matches at least n and at most m of the preceding group.
o {n,m}? or *? or +? performs a nongreedy match of the preceding group.
o ^spam means the string must begin with spam.
o spam$ means the string must end with spam.
o The . matches any character, except newline characters.
o \d, \w, and \s match a digit, word, or space character, respectively.
o \D, \W, and \S match anything except a digit, word, or space character,
respectively.
o [abc] matches any character between the brackets (such as a, b, or c).
o [^abc] matches any character that isn’t between the brackets.

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 12


Python Programming (21EC643) - Module 3:
Pattern Matching with Regular Expressions & Reading and Writing Files

Chapter 8 : Reading and Writing Files

8.1 Intorduction
o Variables in the programs are store data while program is running.
o But if we want our data to persist even after our program has finished, we need
to save it to a file.
o Python also supports file handling and allows users to handle files, i.e. read and
write files, along with many other file handling options.
8.2 Files and File Paths
 What is File?
- File is a named location on disk to store related information.
- File is an object on a computer that stores data, information, settings, or
commands used with a computer program.
- A file has two key properties: a filename and a path.
- The part of the filename after the last period is called the file’s extension and
tells you a file’s type.
- Example: project.docx is a Word document.

 What is File Paths?


- A path is a string of characters used to uniquely identify a location in a
directory structure.
- A path refers to the specific location or route through which a file or directory
can be accessed within a file system
- Folders can contain files and other folders.
- Example: C:\Users\KVGDC\Desktop\Python-6th EC-21 Scheme\Module 3
Python 21EC643

8.3 Backslash on Windows and Forward Slash on OS X and Linux


o On Windows, paths are written using backslashes (\) as the separator
between folder names.
o OS X and Linux, however, use the forward slash (/) as their path separator.
o If you want your programs to work on all operating systems, you will have to
write your Python scripts to handle both cases.

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 13


Python Programming (21EC643) - Module 3:
Pattern Matching with Regular Expressions & Reading and Writing Files

o Example for path: C:\Users\asweigart\Documents\project.docx

 os.path.join() function:***
o The os.path.join() function is helpful to create strings for filenames.Example

o If you os.path.join() will return a string with a file path using the correct path
separators. The following example joins names from a list of filenames to the end
of a folder’s name:

 The Current Working Directory (cwd)


o The current working directory(cwd) is the directory where all the commands are
being executed.
o Every program that runs on our computer has a current working directory(cwd).
o Any filenames or paths that do not begin with the root folder are assumed to be
under the current working directory.
 os.getcwd() and os.chdir().
o The os.getcwd() method returns the current working directory. This method
returns the path from the system's root directory.
o os.chdir() method in Python used to change the current working directory to
specified path. It takes only a single argument as new directory path.

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 14


Python Programming (21EC643) - Module 3:
Pattern Matching with Regular Expressions & Reading and Writing Files

o Example:

 Absolute vs. Relative Paths: There are two ways to specify a file path.
1. Absolute path:
 It always begins with the root folder.
 Absolute paths ensure that Python can find the exact file on your
computer.
 Example: D:\User\Python program\chapter 1\files1.txt
2. Relative path:
 It is relative to the program’s current working directory(cwd).
 relative paths hold less information than absolute paths
 For example:..\home\sally\statusReport.txt

 Creating New Folders with os.makedirs()


o We can create new folders (directories) with the os.makedirs() function.
o Example:

o This will create not just the C:\Suresh folder but also a python folder inside C:\
and module 2 folder inside folder python
o Finally C:\Suresh\python\module 2 new folder is created with absolute path.

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 15


Python Programming (21EC643) - Module 3:
Pattern Matching with Regular Expressions & Reading and Writing Files

8.4 The os. path Module***


o The os. path module contains many helpful functions related to filenames and
file paths.
o The following functions can be carried out using os. path module
1. Handling Absolute and Relative Paths
2. Finding File Sizes and Folder Contents
3. Checking Path Validity

1. Handling Absolute and Relative Paths


o The os. path module provides functions for returning the absolute path of a
relative path. It checks whether a given path is an absolute path.
 os.path.abspath(path):
o It Will return a string of the absolute path of the argument.
o This is an easy way to convert a relative path into an absolute one.
 os. path.isabs(path):
o It will return True if the argument is an absolute path and False if it
is a relative path.
 os.path.relpath(path, start):
o It will return a string of a relative path from the start path to the
path.
o If start is not provided, the current working directory is used as the
start path.
o Since C:\Users was the working directory when os.path.abspath() was called,
the “single-dot” folder represents the absolute path 'C:\\Users'. Example:

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 16


Python Programming (21EC643) - Module 3:
Pattern Matching with Regular Expressions & Reading and Writing Files

 os.path.dirname(path) & os.path.basename(path) methods


a) os.path.dirname(path):It will return a string of everything that comes
before the last slash in the path argument.
b) os.path.basename(path):It will return a string of everything that comes
after the last slash in the path argument. The dirname and base name of a
path are outlined in Figure below.

o For example, enter the following into the interactive shell to find base and
directory name.

 os.path.split()function
o os.path.split() method in Python is used to split the path name into a
pair root and extension.
o os.path.split() to get a tuple value with directory and base strings. It is a nice
shortcut if you need both values.
o Example:

o It creates the same tuple by calling os.path.dirname() and os.path.basename()


and placing their return values in a tuple.

o Note:os.path.split() does not take a file path and returns a list of strings of
each folder.

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 17


Python Programming (21EC643) - Module 3:
Pattern Matching with Regular Expressions & Reading and Writing Files

o For that, use the split() string method and split on the string in os.path.sep.
Recall from earlier that the os.sep variable is set to the correct folder-
separating slash for the computer running the program.Example

o The split() string method will work to return a list of each part of the path. It
will work on any operating system if you pass it os.path.sep.

2. Finding File Sizes and Folder Contents


o The os.path module provides functions for finding the size of a file in bytes
and the files and folders inside a given folder.
• os.path.getsize(path): It will return the size in bytes of the file in the path
argument. Example

• os.listdir(path):It will return a list of filename strings for each file in the
path argument.

3. Checking Path Validity


o Many python functions will crash with an error if you supply them with a path
that does not exist.
o The os.path module provides functions to check whether a given path exists
and whether it is a file or folder by following functions.
a. os.path.exists(path):It will return True if the file or folder referred to
in the argument exists and will return False if it does not exist.
b. os.path.isfile(path):It will return True if the path argument exists and
is a file and will return False otherwise.
c. os.path.isdir(path): It will return True if the path argument exists and
is a folder and will return False otherwise.

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 18


Python Programming (21EC643) - Module 3:
Pattern Matching with Regular Expressions & Reading and Writing Files

 Example:

8.5 The File Reading / Writing Process***


 Types of Files: There are mainly TWO types of data files
1. Text file:
- Stores the data in the form of string .
- A text file consists of human readable characters, which can be opened by any
text editor.
- Example: “Raj” is stored as 3 characters. 890.45 is stored as 6 characters.
- File format: .txt, .c, .cpp, .py
2. Binary file:
- Stores in the form of bytes.
- Binary files are made up of non-human readable characters and symbols,
which require specific programs to access its contents.
- Example: “Raj” is stored as 3 bytes. 89000.45 is stored as 8 bytes
- File format: .jpg, .gif or .png
 Advantages of files
o Data is stored permanently
o Updating becomes easy
o Data can be shared among various programs
o Huge amount of data can be stored
 File operation : In Python, a file operation take place in the following order
1. Open a file
2. Read, write or append (perform operation)
3. Close the file

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 19


Python Programming (21EC643) - Module 3:
Pattern Matching with Regular Expressions & Reading and Writing Files

1. Opening Files with the open() Function


o To open a file with the open() function.
o Pass it a string path indicating the file want to open; it can be either an
absolute or relative path.
o The open() function returns a File object.
o Example: Creating a text file named hello.txt using Notepad or TextEdit

2. Reading the Contents of Files: Following Functions are used for read
operations.
i. read(): reading the content of the file.
ii. read(integer): Read Only Parts of the File, can also specify how many
characters you want to return
iii. readline(): Read one line of the file, calling 2 times to read two lines.
iv. readlines(): read all lines from the file.

 read(): reading the content of the file. I have stored the content in the file
hello.txt

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 20


Python Programming (21EC643) - Module 3:
Pattern Matching with Regular Expressions & Reading and Writing Files

Syntax Program Output


open
( filename,
mode )

 read(+ integer): Read Only Parts of the File, can also specify how many characters
you want to return
Syntax Program Output
open
( filename,
mode )

 readline(): Read one line of the file.


Syntax Program Output
open
( filename,
mode )

 readlines(): read all lines from the file.


Syntax Program Output
open
( filename,
mode )

3. Writing to Files: Two modes for write operation:


1. Write mode ‘w’: replace the old data with new data
2. Append mode ‘a’: append the new data with old data
 Syntax: f= open (‘filename’, ’w’)
f.write(‘Happy day!’)
f.close()
f= open (‘filename’, ‘a’)
f.write(‘Happy day!’)
f.close()

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 21


Python Programming (21EC643) - Module 3:
Pattern Matching with Regular Expressions & Reading and Writing Files

o If the filename passed to open() does not exist, both write and append mode will
create a new, blank file.
o After reading or writing a file, call the close() method before opening the file
again .
o Example Write Mode:
Syntax Program Output
open
( filename,
mode )

o Example append Mode:


Syntax Program Output
open
( filename,
mode )

8.6 Saving Variables with the shelve Module


o The Shelve module is used to store data when using a relational database is not
recommended.
o A shelf object is a dictionary-like object.
o Save variables in Python programs to binary shelf files using the shelve module
o The shelve module will let you add Save and Open features to your program.

8.7 Saving Variables with the pprint.pformat() Function


o The pprint module provides a capability to “pretty-print” arbitrary Python data
structures in a well-formatted and more readable way!
o pprint.pprint() function: will “pretty print” the contents of a list or dictionary to
the screen,

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 22


Python Programming (21EC643) - Module 3:
Pattern Matching with Regular Expressions & Reading and Writing Files

o while the pprint.pformat() function will return this same text as a string instead
of printing it.
o Pprint (pretty print) is a Python module used for formatting complex data
structures more readably and organized, especially when printing them to the
console or writing to a file.
o Using pprint.pformat() will give you a string that you can write to .py file.
o This file will be your very own module that you can import whenever you want
to use the variable stored in it.
o Example:

 Acknowledgement:
My sincere thanks to the author Al Sweigart, because the above contents are prepared from his
textbook “Automate the Boring Stuff with Python: Practical Programming for Total
Beginners”

Prepared by:
Dr. Suresha V
Professor & Principal
Dept. of Electronics and Communication Engineering.
Reach me at: [email protected]
WhatsApp: +91 8310992434

Dr. Suresha V, Professor, Dept. of E&C. K V G C E, Sullia, D.K-57432 Page 23

You might also like