0% found this document useful (0 votes)
35 views115 pages

IPP Module 3

Module 3 of the Introduction to Python Programming course covers string manipulation, including string literals, escape characters, and useful string methods. It also introduces reading and writing files, detailing the file reading/writing process and various projects such as generating random quiz files. Key concepts include indexing and slicing strings, using operators, and applying string methods for various tasks.

Uploaded by

GAJANAN M NAIK
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)
35 views115 pages

IPP Module 3

Module 3 of the Introduction to Python Programming course covers string manipulation, including string literals, escape characters, and useful string methods. It also introduces reading and writing files, detailing the file reading/writing process and various projects such as generating random quiz files. Key concepts include indexing and slicing strings, using operators, and applying string methods for various tasks.

Uploaded by

GAJANAN M NAIK
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/ 115

BPLCK105B/205B : Introduction to Python Programming

Module - 3
Manipulating Strings: Working with Strings, Useful String Methods, Project: Password Locker, Project: Adding Bullets to Wiki Markup

Reading and Writing Files: Files and File Paths, The os.path Module, The File Reading/Writing Process, Saving Variables with the
shelve Module,Saving Variables with the print.format() Function, Project: Generating Random Quiz Files, Project: Multiclipboard.
MODULE 3
MANIPULATING STRINGS
READING AND WRITING FILES

2
A string is a collection of one or more
characters put in a single quote, double-
quote
or triple quote.

3
String Literals

Typing string values in Python code is fairly


straightforward: They begin and end with a single
quote.

But then how can you use a quote inside a


string? Typing
'That is Alice's cat.’
won’t work because Python thinks the string ends after
Alice, and the rest (s cat.') is invalid Python code.

4
String Literals

5
String Literals

● There are multiple ways to type strings


● Double Quotes
● Strings can begin and end with double quotes, just as
they do with single quotes.
● One benefit of using double quotes is that the string can
have a single quote character in it.

● >>> spam = "That is Alice's cat."


6
String Literals

7
String Literals

● spam = "Say hi to Bob's mother. spam = """Say hi to Bob's


● I will be coming" mother. I will
be coming"""
● spam
spam
Cell In[13], line 1
spam = "Say hi to Bob's mother. "Say hi to Bob's
^
SyntaxError: unterminated string
mother.
literal (detected at line 1) I will be coming"
8
9
10
String Literals
● However, if you need to use both single quotes and
double quotes in the string, you’ll need to use escape
characters.
Escape Characters
An escape character lets you use characters that are otherwise
impossible to put into a string.
An escape character consists of a backslash (\) followed by the
character you want to add to the string.

>>> spam = 'Say hi to Bob\'s mother.'

11
12
String Literals

● Python knows that


● since the single quote in Bob\'s has a backslash, it is
not a single quote meant to end the string value.
● The escape characters \' and \" let you put single quotes
and double quotes inside your strings, respectively.

13
Escape Characters

● Escape character Prints as


● \’ Single quote
● \" Double quote
● \t Tab
● \n Newline (line break)
● \\ Backslash

14
String Literals

● >>> print("Hello there!\nHow are


you?\nI\'m doing fine.")
● Hello there!
● How are you?
● I'm doing fine.

15
Raw Strings
● You can place an r before the beginning quotation
mark of a string to make it a raw string.
● A raw string completely ignores all escape characters and
● prints any backslash that appears in the string.
● For example, type the following into the interactive shell:

>>> print(r'That is Carol\'s


cat.')
That is Carol\'s cat. >>>print(‘that is carol\’s cat’)
Output:
that is carol’s cat 16
Raw Strings

● Because this is a raw string, Python considers the backslash


as part of the string and not as the start of an escape
character.

● Raw strings are helpful if you are typing string values that contain
many backslashes

17
Multiline Strings with Triple Quotes
• While you can use the \n escape character to put a
newline into a string, it is often easier to use multiline
strings.
• A multiline string in Python begins and ends with
either three single quotes or three double quotes.
• Any quotes, tabs, or newlines in between the
“triple quotes” are considered part of the string.
‘’’ ‘’’ or “”” 18
Multiline Strings with Triple Quotes

● >>>print('''Dear Alice,
● Eve's cat has been arrested for catnapping, cat
burglary, and extortion.
● Sincerely, Bob''')

Dear Alice,
Need not use escape
Eve's cat has been arrested for catnapping, cat
burglary, and extortion.
Sincerely,Bob 19
Multiline Comments

• While the hash character(#) marks the beginning of a comment for


the rest of the line.
• A multiline string is often used for comments that span multiple lines.

20
Multiline Comments
● """This is a test Python program.
● Written by Al Sweigart [email protected]
● This program was designed for Python 3, not Python 2.
● ""“

● def spam():
● """This is a multiline comment to help
● explain what the spam() function does."""
● print('Hello!')

spam()
'Hello! 21
Indexing and Slicing Strings

• Strings use indexes and slices the same way lists do.
'Hello world!'
You can think of the string 'Hello world!' as a list and each
character in the string as an item with a corresponding
index.
'H e l l o w o r l d !‘
0 1 2 3 4 5 6 7 8 9 10 11

22
Indexing and Slicing Strings

'H e l l o w o r l d !‘
0 1 2 3 4 5 6 7 8 9 10 11
>>> spam = 'Hello
>>> spam[0:5]
world!'
'Hello’
>>> spam[0]
>>> spam[:5]
'H'
'Hello’
>>> spam[4]
>>> spam[6:0]
'o'
‘world’
>>> spam[-1]
'!'
23
Indexing and Slicing Strings

If you specify an index, you’ll get the character at that


position in the string. >>> spam[0] 'H'

If you specify a range from one index to another, the starting


index is included and the ending index is not.
>>> spam = 'Hello world!’,
spam[0:5] is 'Hello’.

The substring you get from spam[0:5] will include everything


from spam[0] to spam[4], leaving out the space at index 5.
24
Indexing and Slicing Strings

● Slicing a string does not modify the original string.


● You can capture a slice from one variable in a
separate variable.

>>> spam = 'Hello world!'


>>> fizz = spam[0:5]
>>> fizz
'Hello'
25
The ‘in’ and ‘not in’ Operators with Strings

• The in and not in operators can be used with strings just like
with list values.
• An expression with two strings joined using in or not in will
evaluate to a Boolean True or False

>>> 'Hello' in 'Hello >>> '' in 'spam'


World' True
True >>> 'cats' not in 'cats and
>>> 'Hello' in 'Hello'
True
dogs'
>>> 'HELLO' in 'Hello False
World' 26
False
Useful String Methods

• upper() • startswith()
• lower() • endswith()
• isupper() • join()
• islower() • split()
• Xstring • rjust()
• isalpha() • ljust()
• isalnum() • center()
• isdecimal() • strip()
• isspace() • rstrip()
• istitle() • lstrip()

27
The upper(), lower(), isupper(), and
islower() String Methods

• The upper() and lower() string methods return a new


string

• All the letters in the original string have been


converted to uppercase or lowercase.

• Nonletter characters in the string remain


unchanged. 28
The upper(), lower(), isupper(), and
islower() String Methods

>>> spam = 'Hello world!'


>>> spam = spam.upper()
>>> spam
'HELLO WORLD!’

>>> spam = spam.lower()


>>> spam
'hello world!'
29
The upper(), lower()
String Methods

The upper() and lower() methods are helpful if you


need to make a case-insensitive comparison.
The strings 'great' and 'GREat' are not equal to
each other.

30
The upper(), lower()
String Methods

But in the following small program, it does not


matter whether the user types Great, GREAT, or
grEAT, because the string is first converted to
print('How
lowercase.are you?') Adding code to your program to
feeling = input() handle variations or mistakes in
if feeling.lower() == 'great': user input, such as inconsistent
capitalization, will make your
print('I feel great too.') programs easier to use and less
else: likely to fail.
print('I hope the rest of your day is
good.') 31
isupper(), and islower() String Methods

• The isupper() and islower() methods will return a


Boolean True value
• if the string has at least one letter and all the
letters are uppercase or lowercase,
respectively.
• Otherwise, the method returns False.

32
isupper(), and islower() String Methods

• The isupper() and islower() methods will return a


Boolean True value
• if the string has at least one letter and all the
letters are uppercase or lowercase,
respectively.
• Otherwise, the method returns False.

33
isupper(), and islower() String Methods

>>> spam = 'Hello


world!' >>>
>>> spam.islower() '12345'.islower()
False
>>> spam.isupper()
False
False >>>
>>> 'HELLO'.isupper() '12345'.isupper()
True False
>>>
'abc12345'.islower() 34
isupper(), and islower() String Methods

>>> 'Hello'.upper()
'HELLO'
>>> 'Hello'.upper().lower() Along with islower() and isupper(),
there are several string
'hello' methods that have names
beginning with the word is.
>>> These methods return a
'Hello'.upper().lower().upper() Boolean value that describes
the nature of the string
'HELLO'
>>> 'HELLO'.lower()
'hello'
>>> 'HELLO'.lower().islower()
35
True
isupper(), and islower() String Methods

 isalpha() returns True if the string consists only of letters


and is not blank.

 isalnum() returns True if


the string consists only of
letters and numbers and is not blank.

 isdecimal() returns True if


the string consists only of
numeric characters and is not blank.

36
isupper(), and islower() String Methods

isspace() returns True if the string consists only of


spaces, tabs, and newlines and is not blank.
istitle() returns True if the string consists only of
words that begin with an uppercase letter
followed by only lowercase letters.
Enter the following into the interactive shell:

37
The isX String Methods

>>> 'hello'.isalpha() >>> ' '.isspace()


True True
>>> >>> 'This Is Title Case'.istitle()
'hello123'.isalpha() True
>>> 'This Is Title Case 123'.istitle()
False
True
>>> >>> 'This Is not Title Case'.istitle()
'hello123'.isalnum() False
True >>> 'This Is NOT Title Case
>>> 'hello'.isalnum() Either'.istitle()
True False
>>> '123'.isdecimal() 38
The isX String Methods

● isalnum()
● This method checks if a string consists only of alphanumeric
characters (letters or digits) and returns a boolean value. For
example:

str1 = "Hello123"
str2 = "Hello!"
print(str1.isalnum()) # Output:
True
print(str2.isalnum()) # Output:
False
39
The isX String Methods

● isalpha()
● This method checks if a string consists only of alphabetic characters
(letters) and returns a boolean value.

str1 = "Hello"
str2 = "Hello123"
print(str1.isalpha()) # Output:
True
print(str2.isalpha()) # Output:
False
40
The isX String Methods

● isdigit()
● This method checks if a string consists only of digits and returns a
boolean value.

str1 = "123"
str2 = "Hello123"
print(str1.isdigit()) # Output: True
print(str2.isdigit()) # Output: False

41
The isX String Methods

● islower():
● This method checks if all the characters in a string are lowercase and
returns a boolean value.

str1 = "hello"
str2 = "Hello"
print(str1.islower()) # Output: True
print(str2.islower()) # Output: False

42
The isX String Methods

● isupper()
● This method checks if all the characters in a string are uppercase and
returns a boolean value.

str1 = "HELLO"
str2 = "Hello"
print(str1.isupper()) # Output: True
print(str2.isupper()) # Output: False

43
The isX String Methods

● isspace()
● This method checks if a string consists only of whitespace characters
and returns a boolean value.

str1 = " "


str2 = "Hello"
print(str1.isspace()) # Output: True
print(str2.isspace()) # Output: False

44
.split()

● The .split() method returns a list of substrings obtained by


splitting the original string based on the specified delimiter.
string.split(separator, maxsplit)
•separator (optional): This parameter specifies the delimiter used to
split the string. If not provided, the default delimiter is a whitespace
character.
•maxsplit (optional): This parameter determines the maximum
number of splits to perform.
•If specified, the string is split at most maxsplit - 1 times. If not
provided, all occurrences of the delimiter are considered for splitting.
45
.split()
● # Splitting a string using a space as the delimiter
● string1 = "Hello world, how are you?"
● words = string1.split()
● print(words)
● # Output: ['Hello', 'world,', 'how', 'are', 'you?']

● # Splitting a string using a comma as the delimiter


● string2 = "apple,banana,orange"
● fruits = string2.split(',')
● print(fruits)
● # Output: ['apple', 'banana', 'orange']
46
.split()

● # Splitting a string with a specified maximum number of splits


● string3 = "one,two,three,four,five"
● limited_splits = string3.split(',', 3)
● print(limited_splits)
● # Output: ['one', 'two', 'three', 'four,five']

47
Python String join() Method

48
String ljust() Method

Syntax
string.ljust(length, character)

49
String replace() Method
Syntax
string.replace(oldvalue, newvalue)
Python String Methods (w3schools.com)

Replace the word "bananas":

String zfill() Method

50
READING AND WRITING
FILES

51
INTRODUCTION
 Fileis a named location on the system storage which records data for later
access. It enablespersistentstorage in a non-volatilememory i.e. Hard disk.
 It is required to work with files for either writingto a file or read data from it. It is
essentialto store the files permanently in secondarystorage.

 In python,file processingtakes place in the followingorder.


• Open a file that returns a file handle.
• Use the handle to perform read or write action.
• Close the file handle.
52
Files and File Paths
• A file has two key properties: a filename (usually written as one word) and a
path.
• filename projects.docx in the path C:\Users\asweigart\Documents.

53
Backslash on Windows & Forward
Slash on OS X & Linux
• On Windows, paths are written using backslashes (\) as the separator between folder
names
• OS X and Linux, however, use the forward slash (/) as their
path separator.

54
Backslash on Windows & Forward
Slash on OS X & Linux
• The / math division operator to join paths correctly, no matter what operating system
your code is running on.

55
Backslash on Windows & Forward
Slash on OS X & Linux
• Keep in mind when using the / operator for joining paths is that one of the first two
values must be a Path object. Python will give you an error if you try entering the
following into the interactive shell:

56
The Current Working Directory

• Current working directory, or cwd


• You can get the current working directory as a string value with the Path.cwd()
function and change it using os.chdir()

57
The Current Working Directory

Python will display an error if you try to change to a directory that does
not exist.

58
The Home Directory

All users have a folder for their own files on the computer called the home
directory or home folder. You can get a Path object of the home folder by
calling Path.home()

The home directories are located in a set place depending on your operating
system:

On Windows, home directories are under C:\Users.


On Mac, home directories are under /Users.
On Linux, home directories are often under /home. 59
Absolute vs Relative Paths

• An absolute path, which always begins with the root folder


• A relative path, which is relative to the program’s current working
directory
• There are also the dot (.) and dot-dot (..) folders.
• A single period (“dot”) for a folder name is shorthand for
• “this directory.” Two periods (“dot-dot”) means “the parent folder.”

60
Absolute vs Relative Paths

61
The os.path Module

The os.path module also has some useful functions related to


absolute and relative paths:

• Calling os.path.abspath(path) will return a string of the absolute


path of the argument. This is an easy way to convert a relative path
into an absolute one.
• Calling os.path.isabs(path) will return True if the argument is an
absolute path and False if it is a relative path.
• Calling os.path.relpath(path, start) will return a string of a relative
path from the start path to path. If start is not provided, the current
working directory is used as the start path.

62
The os.path Module

63
The os.path Module

Enter the following calls to os.path.relpath() into the interactive shell

When the relative path is within the same parent folder as the path, but is within
subfolders of a different path, such as 'C:\\Windows' and 'C:\\spam\\eggs', you can use
the “dot-dot” notation to return to the parent folder.
64
Getting the Parts of a File Path
Given a Path object, you can extract the file path’s different parts as strings using
several Path object attributes.

65
Getting the Parts of a File Path

The parts of a file path include the following:

• The anchor, which is the root folder of the filesystem


• On Windows, the drive, which is the single letter that often
denotes a physical hard drive or other storage device
• The parent, which is the folder that contains the file
• The name of the file, made up of the stem (or base name) and
the suffix (or extension)

66
Getting the Parts of a File Path

To extract each attribute from


the file path, enter the
following into the interactive
shell

These attributes evaluate to


simple string values, except
for parent, which evaluates to
another Path object.

67
Getting the Parts of a File Path

The parents attribute (which is


different from the parent
attribute) evaluates to the
ancestor folders of a Path
object with an integer index:

68
Base name

To create the same tuple by calling os.path.dirname() and


os.path.basename() and placing their return values in a tuple

69
Base name
os.path.split() does not take a file path and return a list of strings of each folder. For that, use the split() string method and split on
the string in os.sep. (Note that sep is in os, not os.path.)

70
Finding File Sizes & Folder Contents

• Calling os.path.getsize(path) will return the size in bytes of the file in the path argument.
• Calling os.listdir(path) will return a list of filename strings for each file in the path
argument. (Note that this function is in the os module, not os.path.)

71
Finding File Sizes & Folder Contents

To find the total size of all the files in this directory, I can use os.path.getsize() and os.listdir()
together

72
Modifying a List of Files Using Glob Patterns

To find the total size of all the files in this directory, I can use os.path.getsize() and os.listdir()
together

73
Checking Path Validity
• Many Python functions will crash with an error if you supply them with a path that does not
exist.
• The os.path module provides functions to check whether a given path exists and whether it
is a file or folder.
• Assuming that a variable p holds a Path object, you could expect the following:

• Calling p.exists() returns True if the path exists or returns False if it doesn’t exist.
• Calling p.is_file() returns True if the path exists and is a file, or returns False otherwise.
• Calling p.is_dir() returns True if the path exists and is a directory, or returns False
otherwise.

74
Checking Path Validity
• To determine whether there is a DVD or flash drive currently attached to the computer by
checking for it with the exists() method.

75
The File Reading/Writing Process
• Plaintext files contain only basic text characters and do not include font, size, or color
information.
• Text files with the .txt extension or Python script files with the .py extension are examples of
plaintext files.
• These can be opened with Windows’s Notepad or macOS’s TextEdit application.
• Binary files are all other file types, such as word processing documents, PDFs, images,
spreadsheets, and executable programs.
• If you open a binary file in Notepad or TextEdit,
it will look like scrambled nonsense

76
The File Reading/Writing Process
• The pathlib module’s read_text() method returns a string of the full contents of a text file.
• Its write_text() method creates a new text file (or overwrites an existing one) with the string
passed to it
• The 13 that write_text() returns indicates that
13 characters were written to the file.

77
The File Reading/Writing Process
• Keep in mind that these Path object methods only provide basic interactions with files. The more
common way of writing to a file involves using the open() function and file objects. There are
three steps to reading or writing files in Python:

• Call the open() function to return a File object.


• Call the read() or write() method on the File object.
• Close the file by calling the close() method on the File object.

78
TYPES OF FILES & OPERATIONS ON FILES

Types of Files:

1. TextFiles - All doc files /excel files etc


2. Binary Files - Audio files, VideoFiles, images etc

Operations on File:
 Open
 Close
 Read
 Write
79
OPEN A FILE IN PYTHON
 Toreador writeto a file, you needto openit first. Toopena file in Python,use its built-in
open( ) function. This function returns a file object, i.e., a handle. You can use it to read
or modifythe file.

 open( ) file method:


file_object= open(“file_name” ,” access_mode”)
file_object– Filehandlerthat points to the particularlocationas a referenceto an object
file_name-Name of the file
access_mode-Read/write/appendmode.By default,it is set to read-only <r>.
Ex: file1 = open("app.log", "w") 80
OPEN A FILE IN PYTHON

81
 Python stores a file in the form of bytes on the disk, so you need to decode them in
strings before reading. And, similarly, encode them while writing texts to the file. This is
done automaticallyby PythonInterpreter.
 If the open is successful, the operating system returns us a file handle. The file handle is
not the actual data contained in the file, but instead it is a “handle” that we can use to
read the data. You are given a handle if the requested
file exists and you have the properpermissionsto read
the file.
82
 If the file does not exist, open will fail with a traceback and you will not get a
handle to accessthe contents

 A file opening may causean errordue to some of the reasonsas listedbelow


 File may not exist in the specified path (when we try to read a file)
 Filemay exist, but we may not have a permissionto read/write a file
 Filemight havegot corruptedand may not be in an openingstate 83
FILE MODES
Modes Description
r Opens a file only for reading
rb Opens a file only for reading but in a binary format

w Opens a file only for writing; overwrites the file if the file exists
wb Opens a file only for writing but in a binary format

a Opens a file for appending. It does not overwrite the file, just adds the data in the file, and if file is
not created, then it creates a new file

ab Opens a file for appending in a binary format

r+ Opens a file only for reading and writing


w+ Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the
file does not exist, creates a new file for reading and writing.

a+ Opens a file for both appending and reading. The file pointer is at the end of the file if the file
exists. The file opens in the append mode.
84
TEXT FILES & LINES
A text file can be thought of as a sequence of lines, much like a Python string can be thought of as a sequence of
characters. For example, this is a sample of a text file which records mail activity from various individuals in an
open source project development team:

Tobreakthe fileintolines,thereis a specialcharacter that representsthe “endof the line”called the newline
character. In the textfileeach linecan be separatedusingescape character\n
>>> stuff = 'X\nY’
>>> print(stuff)
X
Y 85
READING THE FILES
When we successfully open a file to read the data from it, the open() function returns the file handle (or an
object reference to file object) which will be pointing to the first character inthe file.

Thereare different waysin which we can read the files in python.


 read( ) //reads all the content
 read(n) // reads only the first n characters
 readline() // reads single line
 readlines() //reads all lines
Where, n isthe numberof bytesto be read
Note: If the file is too large to fit in main memory, you should write your program to read the fileinchunks
usinga for or whileloop.
86
SAMPLE PROGRAMS
readexample.p countlines.p Countchars.p
y y y
f1=open("1.txt",”r”) f1 = open(“1.txt”,”r”) #finds the length of the file
count = 0
# to read first n bytes for line in f1: f1 = open('1.txt')
print("---first four count = count + 1 ch = f1.read()
characters---") print('Line Count:', count) print(len(ch))
print(f1.read(4))
Outpu
# to read a first line t Output
print("---first line---") Line Count: 5
print(f1.readline()) 120

# to read entire file Note: When the file is read using a for loop in this manner,
print("---Entire File---") Python takes care of splitting the data in the file into Note:In the above code it counts the
print(f1.read()) separate lines using the newline character. number of characters along with
newline character(\n)
Outpu
t
---first four characters--- Readlineexample.py
Coro
---first line--- f1=open("1.txt") #by default read
navirus Can Be Stopped Only by mode #to read line wise 1.txt
Harsh Steps print(f1.readline())
print(f1.readline()) Coronavirus Can Be Stopped Only by Harsh
---Entire File--- Steps
Stay at home Output Stay at home
wear a facemask wear a facemask
Clean your hands often Coronavirus Can Be Stopped Only by Harsh Clean your hands often
Monitor your symptoms Steps Stay at home Monitor your symptoms
87
WRITING THE FILES

 Towritea data intoa file,we needto use the mode ‘w’ inopen( ) function.
 The write( ) method is used to write data into a file.

>>> fhand=open(“mynewfile.txt","w")
>>> print(fhand)

<_io.TextIOWrapper name='mynewfile.txt' mode='w' encoding='cp1252'>

 We have two methods for writingdata into a file as shown below


1. write(string)
2. writelines(list)

If the file specified already exists, then the old contents will be erased and it will be ready to write new data
intoit. If the filedoes not exists, then a new filewith the givenname will be created.

88
For example,

Writexample.p write( ) method: It returns number of characters


successfully written into a file. The file object
y
fhand=open("2.txt",'w'
) s="hello how are
you?" also keeps track of position in the file.
print(fhand.write(s))
Output
:

18

writelines() method: Example:This code adds the list of contentsinto the file including\n
Writelist.p
y
food = ["Citrus\n", "Garlic\n", "Almond\n",
"Ginger\n"] my_file = open("immunity.txt", "w")
my_file.writelines(food)

Outpu
t
It creates a file immunity.txt
Citrus
Garlic
Almond
Ginger
89
Example for read binary ‘rb’ and write binary ‘wb’
Imagecopy.py

f1=open("bird.jpg",'rb')
f2=open("birdcopy.jpg",'wb')
for i in f1:
print(f2.write(i))

bird.jpg #input file birdcopy.jpg #output file

90
SEARCHING THROUGH A FILE

 When you are searching through data in a file, it is a very common pattern to read
through a file, ignoring most of the lines and only processing lines which meet a
particularcondition.

 Most of the times, we would like to read a file to search for some specific data within it.
This can be achieved by using some string methodswhile readinga file.
 For example, we may be interested in printing only the line which starts with a
specificcharacter.

91
SEARCH EXAMPLE
Search1.p Search2.p
y y
fhand = open('mbox.txt') Note:find lines where the search string is anywhere in the
for line in fhand: line. Find() method returns either position of a string or
line = line.rstrip() #strips whitespace from right side of a -1
string if line.startswith('From:'):
print(line) fhand = open('mbox.txt')
Or for line in fhand:
line = line.rstrip()
fhand = open('mbox-short.txt') if line.find('@uct.ac.za') == -1: continue
for line in fhand: print(line)
line = line.rstrip()
# Skip 'uninteresting lines' Outpu
if not line.startswith('From:'): t
From: [email protected] Sat Jan 5 09:14:16 2008
continue
# Process our 'interesting' line
print(line) mbox.tx
t
From: [email protected] Sat Jan 5 09:14:16 2008
Outpu Return-Path:
t <[email protected]> From:
From: [email protected] Sat Jan 5 09:14:16 2008 [email protected]
From: [email protected] Subject: [sakai] svn commit:
From: [email protected] Fri Jan 4 16:10:39 2008 From: [email protected] Fri Jan 4 16:10:39 2008
Return-Path: <[email protected]>

92
LETTING THE USER CHOOSE THE FILE NAME
In a real time programming, it is always better to ask the user to enter a name of the file which he/she would like to open,
instead of hard-coding the name of a file inside the program.
Fileuser.py

fname=input("Enter a file name:")


f1=open(fname)
count =0
for line in f1:
count+=1
print("Line Number ",count, ":",
line) print("Total lines=",count)
f1.close()

Output:
Enter a file name:1.txt
Line Number 1 : Coronavirus Can Be Stopped Only by Harsh
Steps Line Number 2 : Stay at home
Line Number 3 : wear a facemask
Line Number 4 : Clean your hands often
Line Number 5 : Monitor your symptoms
Total lines= 5

In this program, the user input filename is received through variable fname, and the same has been used as an argument
to open() method. Now, if the user input is 1.txt (discussed before), then the result would be Total lines=5
Everything goes well, if the user gives a proper file name as input. But, what if the input filename cannot be
opened (Due to some reason like – file doesn‟t exists, file permission denied etc)?
Obviously, Python throws an error. The programmer need to handle such run- time errors as discussed in the next section.
93
USING TRY, EXCEPT AND OPEN
When you try opening the file which doesn’t exist or if a file name is not valid, then the interpreter throws
you an error. Assume that the open call might fail and add recovery code when the open fails as follows:
Tryfile.py
fname = input('Enter the file name: ')
try:
fhand = open(fname)
except:
print('File cannot be opened:', fname)
exit()
count = 0
for line in fhand:
if line.startswith('From:'):
count = count + 1
print('count=', count)

Output1:
Enter the file name: mbox.txt
count= 3

Output2:
Enter the file name: newmbox.txt
File cannot be opened: newmbox.txt

In the above program, the command to open a file is kept within try block. If the specified file cannot be opened due to
any reason, then an error message is displayed saying File cannot be opened, and the program is terminated. If the file
could able to open successfully, then we will proceed further to perform required task using that file. 94
CLOSE A FILE IN PYTHON

 It’s always the best practice to close a file when your work gets finished. However,
Python runs a garbage collector to clean up the unused objects. While closing a file,
the system frees up all resources allocated to it
 The most basic way is to call the Python close() method.

Filepointer.close()
Example:
f = open("app.log“) #
do file operations.
f.close()

95
Saving Variables with the shelve Module

Save variables in your Python programs to binary shelf files using the shelve module

This way, your program can restore data to variables from the hard drive

The shelve module will let you add Save and Open features to your program

For example, if you ran a program and entered some configuration settings, you could save those
settings to a shelf file and then have the program load them the next time it is run.

96
Saving Variables with the shelve Module

97
Saving Variables with the shelve Module
To read and write data using the shelve module, you first import shelve

Call shelve.open() and pass it a filename, and then store the returned shelf value in a variable

You can make changes to the shelf value as if it were a dictionary

When you’re done, call close() on the shelf value

Here, the shelf value is stored in shelfFile

We create a list cats and write shelfFile['cats'] = cats to store the list in shelfFile as a value
associated with the key 'cats' (like in a dictionary)

Then we call close() on shelfFile


98
Saving Variables with the shelve Module

After running the previous code on Windows, you will see three new files in the current working
directory: mydata.bak, mydata.dat, and mydata.dir

These binary files contain the data you stored in your shelf

The format of these binary files is not important; you only need to know what the shelve
module does, not how it does it

The module frees you from worrying about how to store your program’s data to a file

99
Saving Variables with the shelve Module

Here, we open the shelf files to check that our data was stored correctly.

Entering shelfFile['cats'] returns the same list that we stored earlier, so we know that the list is
correctly stored, and we call close()
100
Saving Variables with the shelve Module

Just like dictionaries, shelf values have keys() and values() methods that will return list-like
values of the keys and values in the shelf

Plaintext is useful for creating files that you’ll read in a text editor such as
Notepad or TextEdit, but if you want to save data from your Python
programs, use the shelve module

101
Saving Variables with the pprint.pformat()
Function
1. The pprint.pprint() function will “pretty print” the contents of a list or dictionary to the
screen, while the pprint.pformat() function will return this same text as a string instead of
printing it.

2. Not only is this string formatted to be easy to read, but it is also syntactically correct Python
code.

3. Say you have a dictionary stored in a variable and you want to save this variable and its
contents for future use.

4. Using pprint.pformat() will give you a string that you can write to a .py file.

5. This file will be your very own module that you can import whenever you want to use the
variable stored in it. 102
Saving Variables with the pprint.pformat()
Function

103
Saving Variables with the pprint.pformat()
Function

1. Here, we import pprint to use pprint.pformat().


2. We have a list of dictionaries, stored in a variable cats.
3. To keep the list in cats available even after we close the shell, we use pprint.pformat() to
return it as a string.
4. Once we have the data in cats as a string, it’s easy to write the string to a file, which we’ll call
myCats.py.

5. The modules that an import statement imports are themselves just Python scripts.
6. When the string from pprint.pformat() is saved to a .py file, the file is a module that can be
imported just like any other.

104
Saving Variables with the pprint.pformat()
Function

105
Saving Variables with the pprint.pformat()
Function

1. The benefit of creating a .py file (as opposed to saving variables with the shelve module) is
that because it is a text file, the contents of the file can be read and modified by anyone with a
simple text editor.

2. For most applications, however, saving data using the shelve module is the preferred way to
save variables to a file.

3. Only basic data types such as integers, floats, strings, lists, and dictionaries can be written to
a file as simple text.

4. File objects, for example, cannot be encoded as text.

106
Useful links

• https://nptel.ac.in/courses/106/106/106106212/
• https://www.tutorialspoint.com/python/python_useful
_resources.htm
• http://www.python.org/doc/
• http://diveintopython.org/

107
Write a function to calculate factorial of a number. Develop a program to
compute binomial coefficient (Given N and R).

108
Read N numbers from the console and create a list. Develop a program to
print mean, variance and standard deviation with suitable messages.

109
Read a multi-digit number (as chars) from the console. Develop a
program to print the frequency of each digit with suitable message.

110
111
Develop a program to print 10 most frequently appearing words in a text
file.

112
Develop a program to sort the contents of a text file and write the sorted
contents into a separate text file.

113

You might also like