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

Module3 Strings and File handling-notesshort

Module-3 covers string manipulation and file handling in Python, including string methods, escape characters, and file reading/writing processes. It discusses various string operations such as indexing, slicing, and concatenation, along with practical projects like a password locker and generating quiz files. The module also introduces important string methods and their applications, including isX() methods, join() and split() methods, and the partition() method.

Uploaded by

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

Module3 Strings and File handling-notesshort

Module-3 covers string manipulation and file handling in Python, including string methods, escape characters, and file reading/writing processes. It discusses various string operations such as indexing, slicing, and concatenation, along with practical projects like a password locker and generating quiz files. The module also introduces important string methods and their applications, including isX() methods, join() and split() methods, and the partition() method.

Uploaded by

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

Module-3: Manipulating Strings, Reading and Writing Files

Module-3: MANIPULATING STRINGS & READING & WRITING FILES

Prepared by: Dr. B Latha Shankar, Associate Professor, IEM Department, SIT Tumakuru

Syllabus: 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: Multi-clipboard.
Textbook 1: Chapters 6, 8 08 hrs.

How are string literals in Python defined and utilized within the language?
 String values in Python begin and end with a single /double /triple quotes
 Benefit of using double/triple quotes: string can have a single quote character in it.
>>> spam = "That is Alice's cat“
>>> print(spam)
O/P: That is Alice's cat

 What to do, if need to use both single quotes and double quotes in the string???
 Use escape characters.

What are escape characters in Python, and how do they function to modify the
interpretation of certain characters within strings? Give illustrative examples.
 An escape character lets to 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. Ex: the escape character for a single quote is \'.
 Use this inside a string that begins and ends with single quotes:
>>> spam = 'Say hi to Bob\'s mother.‘
O/P: Say hi to Bob's mother.
>>> print("Hello there!\n How are you?\n I\'m doing fine.")
O/P:
Hello there!
How are you?
I'm doing fine.
Table 3.1 List of escape characters

3-1
Module-3: Manipulating Strings, Reading and Writing Files

How do raw strings differ from regular strings in terms of syntax and functionality?
Explain.
 A raw string completely ignores all escape characters and prints any backslash that appears in the
string. Place an r before the beginning quotation mark of a string to make it a raw string:
>>> print(r ' That is Carol\'s cat.')
O/P: That is Carol\'s cat.

 Raw strings are helpful while typing string values that contain many backslashes, such as the strings
used for Windows file paths like:
>>> r'C:\Users\Al\Desktop'
O/P: 'C:\\Users\\Al\\Desktop'

Discuss: Multiline Strings with Triple Quotes:


 Use multiline strings in print statement instead of using the \n escape character to put a newline
into a string.
 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.
 Python’s indentation rules for blocks do not apply to lines inside a multiline string.
>>> print('''Dear Alice,
Eve's cat has been arrested for catnapping, cat burglary, and extortion.
Sincerely,
Bob''')

O/p:
Dear Alice,
Eve's cat has been arrested for catnapping, cat burglary, and extortion.
Sincerely,
Bob

Discuss the usage of Multiline Comments.


 Hash character (#) marks the beginning of a comment for the rest of one line
 A multiline string is used for comments that span multiple lines.
Ex:
"""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()
O/p:
Hello!

How does string indexing and string slicing work in programming, and what are the key
differences between them when manipulating strings?
1. Indexing: the process of accessing a specific element in a sequence (ex: string or list) using its position
called as index.

3-2
Module-3: Manipulating Strings, Reading and Writing Files

 Consider the string 'Hello, world!' as a list and each character in the string as an item with a
corresponding index.
 The space and exclamation point are included in the character count.
H e l l o , w o r l d !
0 1 2 3 4 5 6 7 8 9 10 11 12
Ex:
>>> spam = 'Hello, world!'
>>> spam[0]
O/p: 'H'

 If an index has a negative value, it counts backward from the end of the string:
>>> spam[-1]
O/p: '!'
H e l l o , w o r l d !
0 1 2 3 4 5 6 7 8 9 10 11 12
-13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
2. Slicing: It enables users to access the specific range of elements of a sequence (Ex: string, list) by
mentioning the indices.
 Syntax: String[start:stop:step] “Start” specifies the starting index of a slice. “Stop” specifies the
ending element of a slice. If you specify a range from one index to another, the starting index is
included and the ending index is not:
>>> spam[0:5]
O/p: 'Hello'
 If you omit the first index (before the colon), the slice starts at the beginning of the string. If you
omit the second index, the slice goes to till the end of the string:
>>> spam[:5] # first index is omitted and hence string starts from beginning
O/p: 'Hello'
>>> spam[7:] #Last index is omitted and hence slice goes till the end of string
O/p: 'world!'
 If you omit both the indices, the slice is a copy of the whole string.
>>> spam[:] # Both the indices omitted and hence the slice is a copy of string
O/p: ‘Hello, world!’
 Note that slicing a string does not modify the original string, because string is immutable.

How the 'in' and 'not in' operators are used to check for membership in strings in Python?
 in or not in will evaluate to a Boolean True or False.
 These expressions test whether the first string (case sensitive) can be found within the second
string.
Ex:
>>> 'Hello' in 'Hello, World'
O/P: True
>>> spam1 = ['hello', 'hi', 'howdy', 'heyas']
>>> 'cat' in spam1
O/P: False
>>> 'howdy' not in spam1
O/P: False

Syntax:
>>> ELEMENTNAME in LISTNAME
>>> ELEMENTNAME not in LISTNAME

How can one effectively embed or concatenate strings within other strings in a
3-3
Module-3: Manipulating Strings, Reading and Writing Files

programming context?
 Strings can be put inside other strings(=obtaining a new string that contains all of the original
strings) using:
1. string concatenation using + operator
Ex:
>>> name = 'Al'
>>> age = 4000
>>> 'Hello, my name is ' + name + '. I am ' + str(age) + ' years old.'
O/p: 'Hello, my name is Al. I am 4000 years old.'

2. String interpolation: %s operator inside the string acts as a marker to be replaced by values
following the string. Benefit: Need not use str() to convert values into string.
Ex:
>>> name = 'Al'
>>> age = 4000
>>> 'My name is %s. I am %s years old.' % (name, age)
O/p: 'My name is Al. I am 4000 years old.'

3. f-string: which is similar to string interpolation except that braces are used instead of %s, with the
expressions placed directly inside the braces. f-strings have an f prefix before the starting quotation
mark:
Ex:
>>> name = 'Al'
>>> age = 4000
>>> f 'My name is {name}. Next year I will be {age + 1}.'
O/p: 'My name is Al. Next year I will be 4001.'

Discuss few String Methods in Python Programming with illustrative example.


 The upper() string method returns a new string where all the letters in the original string have
been converted to uppercase.
 The lower() string method returns a new string where all the letters in the original string have
been converted to lowercase.
 Use: The upper() and lower() methods are helpful to make a case insensitive comparison. They
can be used to handle variations or mistakes in user input, such as inconsistent capitalization.
Ex:
print('How are you?')
feeling = input()
if feeling.lower() == 'great':
print('I feel great too.')
else:
print('I hope the rest of your day is good.')
O/p: How are you?
GREat
I feel great too.
 The isupper()method will return a Boolean True value if the string has at least one letter and all
the letters are uppercase. Otherwise, the method returns False. islower()method will return a
Boolean True value if the string has at least one letter and all the letters are lowercase. Otherwise,
the method returns False.
>>> spam = 'Hello, world!'
>>> spam.islower()
O/p: False
>>> spam.isupper()
O/p: False
>>> 'HELLO'.isupper()
O/p: True
>>> 'abc12345'.islower()
3-4
Module-3: Manipulating Strings, Reading and Writing Files

O/p: True
>>> '12345'.islower()
O/p: False
 The string methods can be called on the strings returned by upper () and lower () string
methods and called as a chain of method calls.
>>> 'Hello'.upper().lower()
O/p: 'hello'
>>> 'Hello'.upper().lower().upper()
O/p: 'HELLO'
>>> 'HELLO'.lower().islower()
O/p: True

Discuss isX() Methods used in Python Programming.


 isX() string methods have names beginning with the word is
 These methods return a Boolean value.

Common isX() string methods:


• isalpha() : Returns True if string consists only of letters and isn’t blank
• isalnum(): Returns True if 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
• 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
Ex:
>>> 'hello'.isalpha()
O/p: True
>>> 'hello123'.isalnum()
O/p: True
>>> '123'.isdecimal()
O/p: True
>>> ' '.isspace()
O/p: True
>>> 'This Is Title Case'.istitle()
O/p: True
>>> 'This Is not Title Case'.istitle()
O/p: False

Develop a program that repeatedly asks users for their age and a password until they
provide valid input.
while True:
print('Enter your age:')
age = input()
if age.isdecimal():
break
print('Please enter a number for your age.')
while True:
print('Select a new password (letters and numbers only):')
password = input()
if password.isalnum():
break
print('Passwords can only have letters and numbers.')
3-5
Module-3: Manipulating Strings, Reading and Writing Files

O/P:
Enter your age:
forty two
Please enter a number for your age.
Enter your age:
42
Select a new password (letters and numbers only):
secr3t!
Passwords can only have letters and numbers.
Select a new password (letters and numbers only):
secr3t

Differentiate between startswith() & endswith() Methods with examples.


 The startswith() method: returns True if the string it is called on begins with the string passed
to the method; otherwise, it returns False
 The endswith() method returns True if the string it is called on ends with the string passed to
the method; otherwise, it returns False
 Use: alternatives to the == equals operator if it is needed to check only whether the first or last
part of the string, rather than the whole thing, is equal to another string.
 Meaning of ‘string called on’ and ‘string passed to’

Ex:
>>> 'Hello, world!‘ . startswith('Hello')
O/p: True
>>> 'Hello, world!'.endswith('world!')
O/p: True

Distinguish between the join() and split() Methods with illustrative examples.
join() method:
 join() method returns a single string got from concatenation of all strings present in the passed
list.
 Use: when a list of strings are to be joined together into a single string.
 The join() method is
 called on a string,
 a list of strings is passed,
 returns single string.
 join() method calls on a string, which will be inserted between each string of list argument during
concatenation.
Ex:
>>> ', '. join(['cats', 'rats', 'bats']) #’called on string’ is a comma, so, o/p has comma as separator
O/p: 'cats, rats, bats'
>>> ' ‘ . join(['My', 'name', 'is', 'Simon']) #’called on string’ is white space, so, o/p has space as separator
O/p: 'My name is Simon'
>>> 'ABC'.join(['My', 'name', 'is', 'Simon']) #’called on string’ is ‘ABC’, so, o/p has ABC as separator
O/p: 'MyABCnameABCisABCSimon'

3-6
Module-3: Manipulating Strings, Reading and Writing Files

split() method:
 The split() method does the opposite, compared to join() method: It takes in a single string
and returns a list of strings.
 By default, the string 'My name is Simon' is split wherever whitespace characters (= space, tab, or
newline characters) are found.
 These whitespace characters are not included in strings in the returned list.
Ex:
>>> 'My name is Simon'.split()
O/p: ['My', 'name', 'is', 'Simon']

 Pass a ‘delimiter string’ to the split() method to split upon, other than at white spaces.
 This passed string should be present in called on string.
Ex:
>>>'MyABCnameABCisABCSimon'.split('ABC')
O/p: ['My', 'name', 'is', 'Simon']
>>> 'My name is Simon'.split('m')
O/p: ['My na', 'e is Si', 'on']

 Use: to split a multiline string along the newline characters.


Ex:
>>> spam = '''Dear Alice,
How have you been? I am fine.
There is a container in the fridge
that is labeled "Milk Experiment."
Please do not drink it.
Sincerely,
Bob'''
>>> spam.split('\n')
O/p:
['Dear Alice,', 'How have you been? I am fine.', 'There is a container in the
fridge', 'that is labeled "Milk Experiment."', 'Please do not drink it.',
'Sincerely,', 'Bob']

Discuss the partition() Method used for Splitting Strings.


 The partition() method can split a string into the text before and after a ‘separator string’.
 This method returns a tuple of three substrings “before,” “separator,” and “after” substrings.
Ex:
>>> 'Hello, world!‘ . partition('w')
O/p: ('Hello, ', 'w', 'orld!')
>>> 'Hello, world!'. partition('world')
O/p: ('Hello, ', 'world', '!')

 If the separator string passed to partition(), occurs multiple times in the ‘called on’ string, the
method splits the string only on the first occurrence:
>>> 'Hello, world!'. partition('o')
O/p: ('Hell', 'o', ', world!')

 If the separator string can’t be found, the first string returned in the tuple will be the entire string,
and the other two strings will be empty:
>>> 'Hello, world!‘ . partition('XYZ')
O/p: ('Hello, world!', ‘ ', ‘ ')

 Use the ‘multiple assignment trick’ to assign the three returned strings to three variables:
>>> before, sep, after = 'Hello, world!'.partition(' ')
>>> before
3-7
Module-3: Manipulating Strings, Reading and Writing Files

O/p: 'Hello,'
>>> after
O/p: 'world!'

 Use: for splitting a string into the parts before and after a particular separator string.

Discuss few string methods for Justifying Text and Removing Whitespace:
 rjust() and ljust() string methods justifies the string they are called on, with spaces inserted
to justify the text.
 First argument to both methods is an integer length for the justified string.
Ex:
>>> 'Hello‘ . rjust(10) # right-justifies 'Hello' in a string of total length 10.
O/p: ‘ Hello' # 'Hello' is of 5 characters, so five spaces will be added to
#its left, with 'Hello' justified right.
>>> 'Hello'.ljust(15) # left-justifies 'Hello' in a string of total length 15.
O/p: 'Hello ‘

 An optional second argument to rjust() and ljust() will specify a fill character other than a
space character:
>>> 'Hello‘.rjust(20, '*')
O/p: '***************Hello'

 The center() string method works like ljust() and rjust() but centers the text rather than
justifying it to the left or right:
>>> 'Hello'.center(20, '=')
O/p: '=======Hello========'

 Use of these methods: to print tabular data in a neatly aligned format with correct spacing.
Demonstrate justifying mathods using a snippet
def printPicnic(itemsDict, leftWidth, rightWidth): #function definition
print('PICNICITEMS'.center(leftWidth+rightWidth, '-')) #prints at center
for k,v in itemsDict.items(): #extracts keys and values from dict.
print(k.ljust(leftWidth, '.')+str(v).rjust(rightWidth))#prints keys left
#justified and values right justified

picnicItems={'sandwitches':4,’apples':12,'cups':4,'cookies':8000}#input data as dict.


printPicnic(picnicItems, 12, 5) #function call; passing dictionary, widths for left
#column and right column of table in o/p.
printPicnic(picnicItems, 20, 6) #Another function call; passing dictionary, widths
# for left column and right column of table in o/p.
O/p:
---PICNICITEMS---
sandwitches. 4
apples...... 12
cups........ 4
cookies..... 8000

-------PICNICITEMS--------
sandwitches......... 4
apples.............. 12
cups................ 4
cookies............. 8000

Removing Whitespace with the strip(), rstrip() and lstrip() Methods:

3-8
Module-3: Manipulating Strings, Reading and Writing Files

 strip(), rstrip() and lstrip() methods are used to cut off whitespace characters (space,
tab, and newline). strip()removes from the both sides, rstrip() removes from right side
and lstrip() removes from left side of a string.

Ex:
>>> spam = ' Hello, World '
>>> spam . strip() # will remove whitespace characters from both the ends
O/p: 'Hello, World'
>>> spam.lstrip() # will remove whitespace characters from left end.
O/p: 'Hello, World '
>>> spam.rstrip() # will remove whitespace characters from right end.
O/p: ' Hello, World'

 An optional second argument to above methods will specify which characters on the ends should
be stripped:
>>> spam = 'SpamSpamBaconSpamEggsSpamSpam'
>>> spam.strip('ampS') # strip occurrences of a, m, p, and capital S from the ends of
the string stored in spam. The order of the characters does
not matter: strip('ampS') will do the same thing as
strip('mapS') or strip('Spam').
O/p: 'BaconSpamEggs'

Explain the useage of ord() and chr() Functions in Python Programming


 Computers store information in the from of binary numbers
 Every text character has a corresponding numeric value called a Unicode code point(ASCII value)
 Use the ord() function to get this code point of a specified one character string:
>>> ord('A')
O/p: 65
>>> ord('4')
O/p: 52
>>> ord('!')
O/p: 33

 Use chr() function to get the one-character string of an integer code point:
>>> ord(65)
O/p: ‘A’

 Use: when it is needed to do an ordering or mathematical operation on characters:


>>> ord('B')
O/p: 66
>>> ord('A') < ord('B')
O/p: True
>>> chr(ord('A'))
O/p: 'A'

Explain Copying and Pasting Strings with the pyperclip Module:


 The pyperclip module has copy() and paste() functions that can send text to and receive text
from computer’s clipboard.
 Sending the output of a program to the clipboard will make it easy to paste it into an email, word
processor, or some other software.
 The pyperclip module does not come with Python. Need to install it, from third-party modules.

3-9
Module-3: Manipulating Strings, Reading and Writing Files

Ex:
>>> import pyperclip
>>> pyperclip.copy('Hello, world!')
>>> pyperclip.paste()
O/p: 'Hello, world!'

READING AND WRITING FILES


 Variables are used to store data while program is running.
 But if once the program has finished running, data entered and results obtained are no longer
available.
 If data and results are needed, then they need to be written to a file and saved.

Differentiate between Files and File Paths.


 A file has two key properties: a filename and a path.
 The path specifies the location of a file on the computer.
 Ex: there is a file in a folder ‘Documents’ in C drive with the filename: project . docx , with path:
C:\Users\Al\Documents\project.docx
 The part of the filename after the last period is called the file’s extension and tells file’s type.
 The filename project.docx is a Word document, and Users, Al, Documents all refer to folders
(=directories).
 Folders can contain files and other folders. Ex:

 ‘project.docx’ is in the Documents folder, which


is inside the ‘Al’ folder, which is inside the
‘Users’ folder
 The C:\ part of the path is the root folder (C:
drive), which contains all other folders.
 Folder names and filenames are not case-
sensitive on Windows

A file in a hierarchy of folders

Discuss the usage of Path() function with illustrative example.

 Use Path() function in the pathlib module. Path() function returns Path object of strings passed
correct to the operating system used.

>>> from pathlib import Path


>>> str(Path('spam', 'bacon', 'eggs')) #pass Path() function to str() function, to
#get with ‘\’
O/p: 'spam\\bacon\\eggs' # backslashes are doubled because each backslash needs
#to be escaped by another backslash character.

 Following code joins filenames to the end of a folder’s name, one at a time:
>>> from pathlib import Path
>>> myFiles = ['accounts.txt', 'details.csv', 'invite.docx']
>>> for filename in myFiles:

3-10
Module-3: Manipulating Strings, Reading and Writing Files

print(Path( r 'C:\Users\Al', filename))#Path() joins filename to given folder

O/p: C:\Users\Al\accounts.txt
O/p: C:\Users\Al\details.csv
O/p: C:\Users\Al\invite.docx

Demonstrate the usage of Operator ‘/’ to Join Paths:


 The / operator (used for division) can also combine Path objects and strings.
 This is helpful for modifying a Path object after creating it with the Path() function.
Ex:
>>> from pathlib import Path
>>> Path('spam') / ('bacon' / 'eggs') #Joins Path (already created) and strings
O/p: WindowsPath('spam/bacon/eggs')
>>> Path('spam') / Path('bacon/eggs') #Joins 2 Paths
O/p: WindowsPath('spam/bacon/eggs')
>>> Path('spam') / Path('bacon','eggs')#Joins 2 Paths of strings
O/p: WindowsPath('spam/bacon/eggs')

 The pathlib module uses the ‘/’ operator to join paths correctly, no matter, on what operating
system code is running.
>>> homeFolder = Path('C:/Users/Al')
>>> subFolder = Path('spam')
>>> homeFolder / subFolder
O/p: WindowsPath('C:/Users/Al/spam')
>>> str(homeFolder / subFolder)
O/p: 'C:\\Users\\Al\\spam'

 Condition: when using the ‘/’ operator for joining paths then, one of the first two values must be
a Path object. Else Python will give an error:
>>> 'spam' / 'bacon' / 'eggs' # one of the first two values is not a Path object
O/p: Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for /: 'str' and 'str'

Explain: i. Current Working Directory(CWD) ii. Home Directory


 Every program running on computer works in a directory called current working directory(cwd)
 Path.cwd() : Gives the cwd as a string
 os.chdir() : Changes the cwd.
Ex:
>>> from pathlib import Path
>>> import os
>>> Path.cwd()
O/p: WindowsPath('C:/Users/Python37')#Path of project.docx is
#C:\Users\Python37\project.docx
>>> os.chdir('C:\\Windows\\System32')
>>> Path.cwd()
O/p: WindowsPath('C:/Windows/System32') #project.docx would be
#C:\Windows\System32\project.docx

 Python will display an error if you try to change to a directory that does not exist.
>>> os.chdir('C:/ThisFolderDoesNotExist')
O/p: Traceback (most recent call last):
File "<stdin>", line 1, in <module>
3-11
Module-3: Manipulating Strings, Reading and Writing Files

FileNotFoundError: [WinError 2] The system cannot find the file specified:


'C:/ThisFolderDoesNotExist'

The Home Directory:


 All users have a folder for their own files on the computer called home directory (home folder)
 Path.home(): Returns a Path object of the home folder
 On Windows, home directories are under C:\Users.
Ex:
>>> Path.home()
O/p: WindowsPath('C:/Users/Al')

What is the distinction between absolute and relative paths in the context of file systems,
and how do they differ in specifying file or directory locations within a computer system?
 There are two ways to specify a file path:
 An absolute path, which always begins with the root folder
 A relative path, which is relative to program’s cwd.
 A single period . (“dot”) =“this directory.” (CWD)
 Two periods .. (“dot dot”) =“the parent folder(directory).”
 When cwd is set to C:\bacon, relative paths for other folders & files are set as : (The
.\ at start of a relative path is optional)
Absolute Path Relative Path

C:\ .. Or ..\
C:\ bacon . Or .\
C:\bacon\fizz . \ fizz
C:\ bacon\ fizz\spam.txt . \ fizz\spam.txt
C:\ bacon\spam.txt . \ spam.txt
C:\ eggs .. \ eggs
C:\ eggs \ spam.txt .. \ eggs\spam.txt

C:\ spam.txt .. \spam.txt

Discuss the functionality of os.makedirs().


 os.makedirs() function: creates new multiple folders so that entire path exists:
>>> import os
>>> os.makedirs('C:\\delicious\\walnut\\waffles') #This will create C:\delicious
#walnut & waffles folders
# so that full path exists
 mkdir() method: used to create one directory:
Ex:
>>> from pathlib import Path
>>> Path(r 'C:\Users\Al\spam') . mkdir() # This can only make one directory at a time

How Absolute and Relative Paths are handled in Python? Discuss.

3-12
Module-3: Manipulating Strings, Reading and Writing Files

 is_absolute() method: Will return True if it represents an absolute path and False if it represents
a relative path when called on a Path object
Ex:
>>> Path.cwd()
O/P: WindowsPath('C:/Users/Al/Python37')
>>> Path.cwd().is_absolute()
O/P: True
>>> Path('spam/bacon/eggs') . is_absolute()
O/P: False

 Two Options are available: To get an absolute path from a relative path:
1.add Path.cwd() / in front of the relative Path object:
>>> Consider relative path: 'my/relative/path')
>>> Path.cwd() / Path('my/relative/path')
O/P: WindowsPath('C:/Users/Al/AppData/Local/Programs/Python/Python37/my/relative/path')

 2. Add Path.home()in front of the relative Path object:


>>> Path.home() / Path('my/relative/path')
O/P: WindowsPath('C:/Users/Al/my/relative/path')

 os.path module functions:


 os.path.abspath(path): will return a string of absolute path of the argument. This is used
to convert easily a relative path into an absolute one.
 os.path.isabs(path): will return True if argument is an absolute path and False if it is a
relative path.
 os.path.relpath(path, start): will return a string of a relative path from start to path. If
start is not provided, the current working directory is used as the start path.
Ex:
>>> os.path.abspath('.')
O/P: 'C:\\Users\\Al\\AppData\\Local\\Programs\\Python\\Python37'
>>> os.path.abspath('.\\Scripts')
O/P: 'C:\\Users\\Al\\AppData\\Local\\Programs\\Python\\Python37\\Scripts'
>>> os.path.isabs('.')
O/P: False
>>> os.path.isabs(os.path.abspath('.'))
O/P: True

Getting the Parts of a File Path:


 The parts of a file path include the following:
 Anchor: The root folder of the file system
 Drive: a single letter that denotes a physical hard
drive or other storage device
 Parent: Folder that contains the file.
 Name of file: Stem( basename) and suffix (extension)

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

 The drive attribute doesn’t include the first backslash.


>>> p = Path('C:/Users/Al/spam.txt')
>>> p.anchor

3-13
Module-3: Manipulating Strings, Reading and Writing Files

O/P: 'C:\\'
>>> p.parent # This is a Path object, not a string.
O/P: WindowsPath('C:/Users/Al')
>>> p.name
O/P: 'spam.txt'
>>> p.stem
O/P: 'spam'
>>> p.suffix
O/P: '.txt'
>>> p.drive
O/P: 'C:'
>>> Path.cwd()
O/P: WindowsPath('C:/Users/Al/AppData/Local/Programs/Python/Python37')
>>> Path.cwd().parents[0]
O/P: WindowsPath('C:/Users/Al/AppData/Local/Programs/Python')
>>> Path.cwd().parents[1]
O/P: WindowsPath('C:/Users/Al/AppData/Local/Programs')
>>> Path.cwd().parents[2]
O/P: WindowsPath('C:/Users/Al/AppData/Local')
>>> Path.cwd().parents[3]
O/P: WindowsPath('C:/Users/Al/AppData')
>>> Path.cwd().parents[4]
O/P: WindowsPath('C:/Users/Al')
>>> Path.cwd().parents[5]
O/P: WindowsPath('C:/Users')
>>> Path.cwd().parents[6]
O/P: WindowsPath('C:/')

Introduce few functions of os.path module.


• dir name: is everything before the last slash.
• base name: follows the last slash in a path and is = the filename.
Ex:
>>> calcFilePath ='C:\\Windows\\System32\\calc.exe'
>>> os.path.basename(calcFilePath)
O/P: 'calc.exe'
>>> os.path.dirname(calcFilePath)
O/P: 'C:\\Windows\\System32‘

• os.path.split() : To get a tuple of path’s dir name and base name together:
>>> calcFilePath = 'C:\\Windows\\System32\\calc.exe‘
>>> os.path.split(calcFilePath)
O/P: ('C:\\Windows\\System32', 'calc.exe')

 Get the same tuple using: os.path.dirname() and os.path.basename() and place their return
values in a tuple:
>>> (os.path.dirname(calcFilePath), os.path.basename(calcFilePath))
O/P: ('C:\\Windows\\System32', 'calc.exe')

 Use the split() string method and split at os.sep: To get a list of strings of each folder.
>>> calcFilePath.split(os.sep)
#returns all the parts of the path as strings
#separately
O/P: ['C:', 'Windows', 'System32', 'calc.exe']

3-14
Module-3: Manipulating Strings, Reading and Writing Files

How do you find the File Sizes and Folder Contents in Python?
 The os.path module provides getsize () function for finding the size of a file in bytes and
listdir() functions for listing the files and folders inside a given folder.
Ex:
>>> os.path.getsize('C:\\Windows\\System32\\calc.exe')
O/P: 27648
>>> os.listdir('C:\\Windows\\System32')
O/P: ['0409', '12520437.cpx', '12520850.cpx', '5U877.ax', 'aaclient.dll',
--snip--
'xwtpdui.dll', 'xwtpw32.dll', 'zh-CN', 'zh-HK', 'zh-TW', 'zipfldr.dll']

 How to find the total size of all the files in this directory?
 Use os.path.getsize() and os.listdir() together.
 Loop over each filename in the C:\Windows\System32 folder, so that the total Size variable is
incremented by the size of each file.
 Along with os.path.getsize(), os.path.join() is used to join the folder name with the
current filename.
 The integer that os.path.getsize() returns is added to value of totalSize.
Ex. program:
>>> totalSize = 0
>>> for filename in os.listdir('C:\\Windows\\System32'):
totalSize = totalSize +
os.path.getsize(os.path.join('C:\\Windows\\System32', filename))
>>> print(totalSize)
O/P: 2559970473

How do you use Glob Patterns to modify Files.


 Glob is a general term used to define techniques to match specified patterns.
 In Python, the glob module is used to retrieve files/pathnames matching a specified pattern
 Path objects use glob() method for listing the contents of a folder according to a glob pattern.
 The glob() method returns a generator object that you’ll need to pass to list() to easily view in
the interactive shell:
>>> p = Path('C:/Users/Al/Desktop')
>>> p.glob('*') 1.
O/P: <generator object Path.glob at 0x000002A6E389DED0>
>>> list(p.glob('*')) # Make a list from the generator.
O/P: [WindowsPath('C:/Users/Al/Desktop/1.png'), WindowsPath('C:/Users/Al/
Desktop/22-ap.pdf'), WindowsPath('C:/Users/Al/Desktop/cat.jpg'),
--snip--
WindowsPath('C:/Users/Al/Desktop/zzz.txt')]
 The asterisk (*) stands for “multiple of any characters,” so p.glob('*') returns a generator of
all files in the path stored in p.
Ex:
>>> list(p.glob('*.txt') # Lists all text files having '.txt' file extension.
O/P: [WindowsPath('C:/Users/Al/Desktop/foo.txt'),
--snip--
WindowsPath('C:/Users/Al/Desktop/zzz.txt')]

 The question mark ‘?’ stands for any single character. The glob expression 'project?.docx' will
return 'project1.docx' or 'project5.docx', but it will not return 'project10.docx', because
‘?’ only matches to one character—so it will not match to two-character string '10'.

3-15
Module-3: Manipulating Strings, Reading and Writing Files

Ex:
>>> list(p.glob('project?.docx')
O/P: [WindowsPath('C:/Users/Al/Desktop/project1.docx'), WindowsPath('C:/Users/Al/
Desktop/project2.docx'),
--snip--
WindowsPath('C:/Users/Al/Desktop/project9.docx')]
 Combine the asterisk and question mark; use the glob expression '*.?x?' to return files with
any name and any three-character extension where the middle character is an 'x'.
 Use a for loop to iterate over the generator that glob() returns:
>>> p = Path('C:/Users/Al/Desktop')
>>> for textFilePathObj in p.glob('*.txt'):
... print(textFilePathObj) # Prints the Path object as a string.
O/P: C:\Users\Al\Desktop\foo.txt
C:\Users\Al\Desktop\spam.txt
C:\Users\Al\Desktop\zzz.txt

 Use: If you want to perform some operation on every file in a directory, use either os.listdir(p)
or p.glob('*').

Discuss Path Validity checking functions.


 Path objects have methods to check whether a given path exists and whether it is a file or folder.
 Assume a variable p that holds a Path object:
 p.exists(): returns True if path exists or returns False if it doesn’t exist.
 p.is_file(): returns True if the path exists and is a file, or returns False otherwise.
 p.is_dir(): returns True if the path exists and is a directory, or returns False otherwise.
Ex:
>>> winDir = Path('C:/Windows')
>>> notExistsDir = Path('C:/This/Folder/Does/Not/Exist')
>>> calcFile = Path('C:/Windows/System32/calc.exe')
>>> winDir.exists()
O/P: True
>>> winDir.is_dir()
O/P: True
>>> notExistsDir.exists()
O/P: False
>>> calcFile.is_file()
O/P: True

 How to determine whether there is a DVD or flash drive currently attached to the computer? By
checking for it with the exists() method.
>>> dDrive = Path('D:/')
>>> dDrive.exists()
O/P: False

Identify the functions used in File Reading/Writing Process.


 Plaintext files contain only basic text characters and do not include font, size, or color information.
 Ex: Text files with the .txt extension and Python script files with the .py extension.
 The pathlib module’s read_text() method: returns the full contents of a text file as a string.
 Its write_text() method: creates a new text file (or overwrites an existing one) with the string
passed to it.
Ex:
>>> from pathlib import Path
3-16
Module-3: Manipulating Strings, Reading and Writing Files

>>> p = Path('spam.txt')
>>> p.write_text('Hello, world!') #creates spam.txt file with content 'Hello,world!'
O/P: 13 # write_text()indicates that 13 characters were written to file.
>>> p.read_text()
O/P: 'Hello, world!' #reads and returns the contents of new file as a string

 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.

Opening Files with the open() Function:


 To open a file with the open() function, pass a path (absolute or relative) of that file as string;
>>> helloFile = open(Path.home() / 'hello.txt') #opens the file with name ‘hello.txt’

 Path.home(): Returns a Path object of the home folder


 open() function returns File object
 The open() function can also accept strings.
Ex:
>>> helloFile = open('C:\\Users\\home_folder\\hello.txt')
 Both above commands (string or Path object) will open the file in read mode.
 Read mode is the default mode for files in Python.
 When a file is opened in read mode, Python lets you only read data from the file; you can’t write
or modify it in any way.
 If needed, you can explicitly specify the mode by passing the string value 'r' as a second argument
to open().
 open('/Users/Al/hello.txt', 'r') and open('/Users/Al/hello.txt') do the same thing.

Reading the Contents of Files:


 read() method: reads the entire contents of a file as a single string value:
>>> helloContent = helloFile.read()
>>> helloContent
O/P: 'Hello, world!'

 readlines() method: returns a list of strings, one string for each line of the file.
Ex:
Create a file named sonnet29.txt in the same directory as hello.txt and write following
text in it:
When, in disgrace with fortune and men's eyes,
I all alone beweep my outcast state,
And trouble deaf heaven with my bootless cries,
And look upon myself and curse my fate.
>>> sonnetFile = open(Path.home() / 'sonnet29.txt')
>>> sonnetFile.readlines() # returns a list of string values, one string for each
#line of the file
O/P: [‘When, in disgrace with fortune and men's eyes,\n', ' I all alone
beweep my outcast state,\n', And trouble deaf heaven with my
bootless cries,\n', And look upon myself and curse my fate.']

 Except for the last line of the file, each of the string values ends with a newline character ‘\n’.

Writing to Files:
 Python allows to write content to a file, similar to how print() function “writes” strings to screen
3-17
Module-3: Manipulating Strings, Reading and Writing Files

 To write contents to a file it has to be opened in ‘write mode’ or ‘append mode’, not in ‘read mode’.
 Pass 'w' as the second argument to open() to open the file in write mode.
 ‘Write mode’ will overwrite the existing file and start from scratch.
Ex:
>>> baconFile = open('bacon.txt', 'w')
>>> baconFile.write('Hello, world!\n')
O/P: 14
>>> baconFile.close()
>>> baconFile = open('bacon.txt', 'a')
>>> baconFile.write('Bacon is not a vegetable.')
O/P: 25
>>> baconFile.close()
>>> baconFile = open('bacon.txt')
>>> content = baconFile.read()
>>> baconFile.close()
>>> print(content)
O/P: Hello, world!
Bacon is not a vegetable.

 Note that the write() method does not automatically add a newline character to the end of the
string like the print() function does. You will have to add this character yourself.
>>> baconFile = open('bacon.txt', 'w')
>>> baconFile.write('Hello, world!\n')
O/p: 14

Elaborate on usage of shelve Module:


 Variables and data used during running a program no longer remains, once the program is closed.
These variables with data and configuration settings used in Python programs can be stored to
shelf files using the shelve module, which can be retrieved from the hard drive when needed.
>>> import shelve
>>> shelfFile = shelve.open('mydata')#pass file ‘mydata’, store returned shelf value
#in a variable
>>> cats = ['Zophie', 'Pooka', 'Simon']
>>> shelfFile['cats'] = cats #Creates dictionary-like object & keys must be strings
>>> shelfFile.close() # When done, close()the shelf file.

 After running the previous code on Windows, three new files in the current working directory will
be visible: mydata.bak, mydata.dat, and mydata.dir.
How to retrieve data from shelve module?
 Use the shelve module to reopen and retrieve the data from saved shelf files.
 Shelf values don’t have to be opened in read or write mode—they can do both once opened.
 Entering shelfFile['cats'] returns the same list that was stored earlier, and use close() to close
it.
>>> shelfFile = shelve.open('mydata')
>>> type(shelfFile)
O/P: <class 'shelve.DbfilenameShelf'>
>>> shelfFile['cats'] # Returns content of list named ‘cats’
O/P: ['Zophie', 'Pooka', 'Simon']
>>> shelfFile.close()

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

3-18
Module-3: Manipulating Strings, Reading and Writing Files

 Since these methods return list-like values instead of true lists, pass them to the list() function
to get them in list form.
>>> shelfFile = shelve.open('mydata')
>>> list(shelfFile.keys())
O/P: ['cats']
>>> list(shelfFile.values())
O/P: [['Zophie', 'Pooka', 'Simon']]
>>> shelfFile.close()

Explain the functionality of pprint.pformat() in Python programming.


 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.
 This string formatted is more readable.
 Ex: you have a dictionary stored in a variable and you want to save this variable and its contents
for future use.
 Using pprint.pformat() will give you a string that you can write to a .py file.
 This file will be your own module that you can import whenever you want to use the variable
stored in it.
Ex:
>>> import pprint
>>> cats = [{'name': 'Zophie', 'desc': 'chubby'}, {'name': 'Pooka', 'desc': 'fluffy'}]
>>> pprint.pformat(cats)
O/P: "[{'desc': 'chubby', 'name': 'Zophie'}, {'desc': 'fluffy', 'name': 'Pooka'}]"
>>> fileObj = open('myCats.py', 'w')
>>> fileObj.write('cats = ' + pprint.pformat(cats) + '\n')
O/P: 83
>>> fileObj.close()

 To keep the list in cats available even after closing the shell, use pprint.pformat() to return it
as a string.
 Once we have the data in cats as a string, it’s easy to write the string to a file, called myCats.py.
 The modules are Python scripts.
 When the string from pprint.pformat() is saved to a .py file, the file can be imported as a module
just like any other:
>>> import myCats
>>> myCats.cats
O/P: [{'name': 'Zophie', 'desc': 'chubby'}, {'name': 'Pooka', 'desc': 'fluffy'}]
>>> myCats.cats[0]
O/P: {'name': 'Zophie', 'desc': 'chubby'}
>>> myCats.cats[0]['name']
O/P: 'Zophie'

 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 editon

Develop a program for Generating Random Quiz Files.


 Develop a Python program to
1. Creates 35 different quizzes

3-19
Module-3: Manipulating Strings, Reading and Writing Files

2. Creates 50 multiple-choice questions for each quiz, in random order


3. Provides the correct answer and three random wrong answers for each question, in random order
4. Writes the quizzes to 35 text files
5. Writes the answer keys to 35 text files
 Solution: The code will do the following:
1. Store the states and their capitals in a dictionary
2. Call open(), write(), and close() for the creating the quiz and answer key text files
3. Use random.shuffle() to randomize the order of the questions and multiple-choice options
Step 1: Store the Quiz Data in a Dictionary
import random
# Store the quiz data in a dictionary called capitals. Keys are states and values
are their capitals.
capitals = {'Alabama': 'Montgomery', 'Alaska': 'Juneau', 'Arizona': 'Phoenix',
'Arkansas': 'Little Rock', 'California': 'Sacramento', 'Colorado': 'Denver',
'Connecticut': 'Hartford', 'Delaware': 'Dover', 'Florida': 'Tallahassee',
'Georgia': 'Atlanta', 'Hawaii': 'Honolulu', 'Idaho': 'Boise', 'Illinois':
'Springfield', 'Indiana': 'Indianapolis', 'Iowa': 'Des Moines', 'Kansas': 'Topeka',
'Kentucky': 'Frankfort', 'Louisiana': 'Baton Rouge', 'Maine': 'Augusta', 'Maryland':
'Annapolis', 'Massachusetts': 'Boston', 'Michigan': 'Lansing', 'Minnesota': 'Saint
Paul', 'Mississippi': 'Jackson', 'Missouri': 'Jefferson City', 'Montana': 'Helena',
'Nebraska': 'Lincoln', 'Nevada': 'Carson City', 'New Hampshire': 'Concord', 'New
Jersey': 'Trenton', 'New Mexico': 'Santa Fe', 'New York': 'Albany‘}'North Carolina':
'Raleigh', 'North Dakota': 'Bismarck', 'Ohio': 'Columbus', 'Oklahoma': 'Oklahoma
City', 'Oregon': 'Salem', 'Pennsylvania': 'Harrisburg', 'Rhode Island':
'Providence', 'South Carolina': 'Columbia', 'South Dakota': 'Pierre',
'Tennessee':'Nashville', 'Texas': 'Austin', 'Utah': 'Salt Lake City',
'Vermont':'Montpelier', 'Virginia': 'Richmond', 'Washington': 'Olympia', 'West
Virginia': 'Charleston', 'Wisconsin': 'Madison', 'Wyoming': 'Cheyenne'}

Step 2: Create the Quiz File and Shuffle the Question Order
# Generate 35 quiz files.
for quizNum in range(35):
quizFile = open(f 'capitalsquiz{quizNum+1}.txt','w') #creates quizfile
#&opens in write mode
answerKeyFile = open(f 'capitalsquiz_answers{quizNum + 1}.txt', 'w')#creates
#quiz answer keyfile &opens in write mode
# Write out the header for the quiz.
quizFile.write('Name:\n\nDate:\n\nPeriod:\n\n') #creates header in quizfile
quizFile.write((' ' * 20) + f 'State Capitals Quiz (Form{quizNum + 1})')
quizFile.write('\n\n')
states = list(capitals.keys()) #creates a list of states from the dictionary
random.shuffle(states) #Shuffles the above list

Step 3: Create the Answer Options


# Loop through all 50 states, making a question for each.
for questionNum in range(50):
# Get right and wrong answers.
correctAnswer =capitals[states[questionNum]]#picks capital as correct ans
wrongAnswers = list(capitals.values()) #picks all capitals
del wrongAnswers[wrongAnswers.index(correctAnswer)] #deletes correct ans
wrongAnswers = random.sample(wrongAnswers,3) #picks3 random wrong answers
answerOptions =wrongAnswers +[correctAnswer] #4 options with 1correct ans
random.shuffle(answerOptions) #Shuffles the above 4 options

Step 4: Write Content to the Quiz and Answer Key Files


# Write the question and the answer options to the quiz file.
3-20
Module-3: Manipulating Strings, Reading and Writing Files

quizFile.write(f'{questionNum + 1}. What is the capital of


{states[questionNum]}?\n')#Writes questions on to quizfile
for i in range(4):
quizFile.write(f" {'ABCD'[i]}. { answerOptions[i]}\n") #'ABCD'[0]=A
quizFile.write('\n')
# Write the answer key to a file.
answerKeyFile.write(f"{questionNum + 1}. #picks the correct ans
{'ABCD'[answerOptions.index(correctAnswer)]}")
quizFile.close()
answerKeyFile.close()

O/p:
Sample quiz paper: capitalsquiz1.txt :

Name:
Date:
Period:
State Capitals Quiz (Form 1)
1. What is the capital of West Virginia?
A. Hartford
B. Santa Fe
C. Harrisburg
D. Charleston
2. What is the capital of Colorado?
A. Raleigh
B. Harrisburg
C. Denver
D. Lincoln
--snip--
Sample Answer Key File: capitalsquiz_answers1.txt :
1. D
2. C
3. A
4. C
--snip--

Develop a program for: Adding Bullets to Wiki Markup

1. Paste text from the clipboard.


2. Add a star and space to the beginning of each line. (Or do something to it)
3. Copy the new text to the clipboard.

For example, if the following text is copied to the clipboard::

Lists of animals
Lists of aquarium life
Lists of biologists by author abbreviation
Lists of cultivars

Output after executing the program should be:


* Lists of animals

3-21
Module-3: Manipulating Strings, Reading and Writing Files

* Lists of aquarium life


* Lists of biologists by author abbreviation
* Lists of cultivars

# This program adds bullet points to the start of each line of text on the clipboard.
Step 1: Copy and Paste from the Clipboard:
import pyperclip
text = pyperclip.paste() # assigns entire text copied as single string to variable text

Step 2: Separate the Lines of Text and Add the Star


lines = text.split('\n') # splits the single string into list of strings at the new line character
for i in range(len(lines)): # loop through all indexes in the "lines" list
lines[i] = '* ' + lines[i] # add star to each string in "lines" list

Step 3: Join the Modified Lines


text = '\n'.join(lines) # joins individual lines into single string again to be copied to clipboard
pyperclip.copy(text) # copies to clipboard.

Please watch the youtube video for further understanding:


https://www.youtube.com/watch?v=QASJoahNYZY

Abstract of string.methods and string related functions, file.methods and file related
functions(for quick reference):
Sl. Command Meaning Example
No.
Manipulating Strings:
1. escape character A backslash \ followed \n: new line
by the character you
want to insert.
2. Raw String completely ignores all >>> print(r ' That is Carol\'s cat.')
escape characters and O/P: That is Carol\'s cat.
prints any backslash that
appears in the string
3. multiline string in print Used to put a newline print('''Dear Alice,
statement into a string instead of \n Eve's cat has been arrested''')
escape character
O/p:
Dear Alice,
Eve's cat has been
arrested
4. multiline string used for comments that """This is a multiline comment."""
span multiple lines print('Hello!')
O/p: Hello!

5. indexing used to access the spam = 'Hello, world!'


element of the string >>> spam[0]
O/p: 'H'

6. slicing return a range of >>> spam[0:5]


characters (a part of the O/p: 'Hello'
3-22
Module-3: Manipulating Strings, Reading and Writing Files

string)
7. in and not in operators tests whether the first >>> spam1 = ['hello', 'howdy']
string (case sensitive) >>> 'cat' in spam1
can be found within the O/P: False
second string. >>> 'cat' not in spam1
O/p: True
8. Joining the strings obtaining a new string >>> name = 'Al'
>>> age = 4000
that contains both of
the original strings:
1. >>> 'Hello, my name is ' + name + '.
I am ' + str(age) + ' years old.'
concatenation:Uses
O/p: 'Hello, my name is Al. I am 4000
‘+’ operator years old.'
2. String >>> 'My name is %s. I am %s years
interpolation: old.' % (name, age)
O/p: 'My name is Al. I am 4000 years
Uses %s operator
old.'
that acts as a marker
to be replaced by
values following the
string
3.f-string: similar >>> f 'My name is {name}. Next year I
will be {age + 1}.'
to string interpolation O/p: 'My name is Al. Next year I will
except that braces are be 4001.'
used instead of %s,
with the expressions
placed directly inside
the braces
String Methods:
9. .upper() Returns all the letters >>> spam = spam.upper()
>>> spam
in the original string to O/p: 'HELLO, WORLD!'
uppercase
10. .lower() Returns all the letters >>> spam = spam.lower()
>>> spam
in the original string to O/p: 'hello, world!'
uppercase
.isX() string methods:
11. .isupper() Returns Boolean True if >>> 'HELLO'.isupper()
string has at least one O/p: True
letter and all the letters
are uppercase else
False.

12. .islower() Returns Boolean True if spam = 'Hello, world!'


string has at least one >>> spam.islower()
O/p: False
letter and all the letters
are lowercase else
returns False.
13. .isalpha() >>> 'hello'.isalpha()
Returns True if string O/p: True
consists only of letters
>>> 'hello123'.isalpha()
O/p: False
3-23
Module-3: Manipulating Strings, Reading and Writing Files

and isn’t blank else


returns False.
14. .isalnum() Returns True if string >>> 'hello123'.isalnum()
consists only of letters O/p: True
and numbers and is not >>> 'hello'.isalnum()
blank else returns False. O/p: True
15. .istitle() Returns True if the >>> 'This Is Title Case'.istitle()
string consists only of O/p: True
words that begin with
an uppercase letter
followed by only
lowercase letters else
returns False.
16. .isspace() Returns True if the >>> ' '.isspace()
string consists only of O/p: True
spaces, tabs, and
newlines and is not
blank else returns False.
17. .isdecimal() Returns True if the >>> '123'.isdecimal()
string consists only of O/p: True
numeric characters >>> 'This Is NOT Title Case
and is not blank else Either'.istitle()
returns False. O/p: False
18. .startswith() Returns True if the >>> 'Hello, world!‘ .
startswith('Hello')
string it is called on O/p: True
begins with the string
passed to the
method; otherwise, it
returns False
19. .endswith() returns True if the >>> 'abc123'.endswith('12')
O/p: False
string it is called on
ends with the string
passed to the
method; otherwise, it
returns False
20. .join() Returns a single string >>> ' ‘ . join(['My', 'name', 'is',
'Simon'])
Calledstring.join
got from O/p: 'My name is Simon'
(passedstring) concatenation of all
strings present in the
passed list.
21. .split() Returns a list of >>> 'My name is Simon'.split()
O/p: ['My', 'name', 'is', 'Simon']
Calledstring.split
strings when called on
a string. >>> 'My name is Simon'.split('m')
(passedstring) O/p: ['My na', 'e is Si', 'on']
22. . partition() Splits a string into the >>> 'Hello, world!‘ . partition('w')
O/p: ('Hello, ', 'w', 'orld!')
text before and after a
‘separator string’
23. Justify the string they >>> 'Hello‘ . rjust(10)
.rjust(), .ljust()and O/p: ‘ Hello'
.center() string methods are called on, with >>> 'Hello'.ljust(15)
3-24
Module-3: Manipulating Strings, Reading and Writing Files

spaces inserted to O/p: 'Hello


>>> 'Hello'.center(20, '=')
justify the text. O/p: '=======Hello========'
24. Used to strip off >>> spam = ' Hello, World '
.lstrip(), .rstrip()
>>> spam.lstrip()
and .strip() whitespace O/p: 'Hello, World '
characters (space,
>>> spam.rstrip()
tab, and newline) O/p: ' Hello, World'
from the right side,
left side and both >>> spam . strip()
O/p: 'Hello, World'
sides of a string
25. Used to get >>> ord('A')
ord()
O/p: 65
corresponding ASCII
value of a specified >>> ord('4')
O/p: 52
one character string
26. chr() Used to get the one- >>> ord(65)
character string of an O/p: ‘A’
integer code point
27. >>> import pyperclip
copy() and paste() Send text to and >>> pyperclip.copy('Hello, world!')
functions of pyperclip receive text from >>> pyperclip.paste()
module computer’s clipboard. O/p: 'Hello, world!'

Reading and writing files:


28. Functions in pathlib and os module
29. Returns Path object of >>> from pathlib import Path
Path()
>>> Path('spam', 'bacon', 'eggs')
strings passed, correct O/p: WindowsPath('spam/bacon/eggs')
to the operating >>> str(Path('spam', 'bacon',
system 'eggs'))
O/p: 'spam\\bacon\\eggs'

30.
/ operator combines Path >>> from pathlib import Path
>>> Path('spam') / 'bacon' / 'eggs')
objects and strings O/p: WindowsPath('spam/bacon/eggs')
31. Path.cwd() Gives the cwd as a >>> from pathlib import Path
>>> import os
string >>> Path.cwd()
O/p:
WindowsPath('C:/Users/Python37')
32. Changes the cwd >>> os.chdir('C:\\Windows\\System32')
os.chdir()
>>> Path.cwd()
O/p:WindowsPath('C:/Windows/System32')
33. Path.home() Returns a Path object >>> Path.home()
O/p: WindowsPath('C:/Users/Al')
of the home folder

34. creates new multiple >>> import os


os.makedirs()
>>>
folders so that entire os.makedirs('C:\\delicious\\walnut\\waff
path exists les')
35. used to create one >>> from pathlib import Path
mkdir()
>>> Path(r 'C:\Users\Al\spam') .
directory: mkdir()

3-25
Module-3: Manipulating Strings, Reading and Writing Files

36.
Add Path.cwd()to relative Used to get an >>> Path('my/path')
path absolute path from O/P: WindowsPath('my/path')
relative path. >>> Path.cwd() / Path('my/path')
O/P: WindowsPath('C:/Users/Al/my/path')
37.
Add Add this to relative
Path.home()to >>> Path('my/path')
relative path path to get an O/P: WindowsPath('my/path')
absolute path from >>> Path.home() / Path('my/path')
relative path. O/P: WindowsPath('C:/Users/Al/my/path')
38. os.path.abspath(path) Returns a string of >>> os.path.abspath('.')
absolute path of the O/P: 'C:\\Users\\Al\\AppData\\Local
argument \\Programs\\Python\\Python37'

39. os.path.isabs(path) Returns True if >>> os.path.isabs('.')


argument is an O/P: False
absolute path and
False if it is a
relative path.
40. os.path.relpath(path, Returns a string of a
start) relative path from start
path to path. If start is
not provided, the
current working
directory is used as the
start path.
41. Returns the root >>> p = Path('C:/Users/Al/spam.txt')
If p has a Path object: >>> p.anchor
folder of the file O/P: 'C:\\'
p.anchor
system
42. p.parent Returns folder that >>> p.parent
contains the file. O/P: WindowsPath('C:/Users/Al')
43. p.name Returns name of file: >>> p.name
Stem( basename) and O/P: 'spam.txt'
suffix (extension)
44. p.stem Returns Stem( >>> p.stem
basename) O/P: 'spam'
45. p.suffix Returns suffix >>> p.suffix
(extension) O/P: '.txt'
46. p.drive Returns drive >>> p.drive
O/P: 'C:'
47. os.path.split() To get a tuple of >>> calcFilePath =
path’s dir name and 'C:\\Windows\\System32\\calc.exe‘
base name together >>> os.path.split(calcFilePath)
O/P: ('C:\\Windows\\System32',
'calc.exe')
48.
. split() at os.sep Returns all the parts >>> calcFilePath.split(os.sep)
O/P: ['C:', 'Windows', 'System32',
of the path as 'calc.exe']
separate strings
49. os.path.getsize() For finding the size of >>> os.path.getsize('C:\\Windows\\
System32\\calc.exe')
a file in bytes
O/P: 27648

3-26
Module-3: Manipulating Strings, Reading and Writing Files

50. Os.listdir() Listing the files and >>> os.listdir('C:\\Windows\\


folders inside a given System32')
folder O/P: ['0409', '12520437.cpx',
'12520850.cpx', '5U877.ax',
--snip--
'xwtpdui.dll', 'xwtpw32.dll', 'zh-
CN', 'zh-HK', 'zh-TW']
51. os.path.join() Used to join the folder os.path.join('C:\\Windows\\
name with the current System32', filename)
filename O/P: 'C:\\Windows\\
System32\\filename’

Glob Patterns
52. .glob() Lists the contents of a
folder according to a
glob pattern
53. The asterisk (*) >>> p = Path('C:/Users/Al/Desktop')
.glob(*)
>>> p.glob('*') 1.
stands for “multiple of O/P: <generator object Path.glob at
any characters”. 0x000002A6E389DED0>
>>> list(p.glob('*'))
glob('*') returns a O/P:
[WindowsPath('C:/Users/Al/Desktop/1.
generator of all files in png'), --snip--
the path stored in WindowsPath('C:/Users/Al/Desktop/zzz
Path. Use .txt')]
list(.glob(*)) to list
all the contents of a
folder.
54. list(p.glob('*.txt') Lists all the files with O/P:
[WindowsPath('C:/Users/Al/Desktop/fo
.txt extension. o.txt'),
--snip--
WindowsPath('C:/Users/Al/Desktop/zzz
.txt')]
55. ‘?’ only matches to >>> list(p.glob('project?.docx')
list(p.glob
O/P:
(' ?.docx')
one character. [WindowsPath('C:/Users/Al/Desktop/pr
oject1.docx'), --snip--
will return WindowsPath('C:/Users/Al/Desktop/pro
'project1.docx' to ject9.docx')]
till 'project5.docx',
but it will not return
'project10.docx'
56. '*.?x?' Returns files with any
name and any three-
character extension
where the middle
character is an 'x'
Checking Path Validity
57.
If p has a Path object: Returns True if path >>> winDir = Path('C:/Windows')
>>> winDir.exists()
exists or returns False O/P: True
p.exists()
if it doesn’t exist

3-27
Module-3: Manipulating Strings, Reading and Writing Files

58. p.is_file() Returns True if the >>> calcFile.is_file()


path exists and is a O/P: True
file, or returns False
otherwise
59. p.is_dir() Returns True if the >>> calcFile.is_dir()
path exists and is a O/P: False
directory, or returns
False otherwise
File Reading/Writing Process: Needs pathlib module
60. open() Function returns File >>> helloFile =
open('C:\\Users\\home_folder\\hello.
object txt')
61. creates a new text file >>> from pathlib import Path
.write_text()
>>> p = Path('spam.txt')
(or if exists overwrites
it) with the string >>> p.write_text('Hello, world!')
passed to it. O/P: 13

62. .read_text() Returns the full >>> p.read_text()


contents of a text file O/P: 'Hello, world!'
as one string
63. Returns the full >>> helloContent = helloFile.read()
.read()
>>> helloContent
contents of a text file O/P: 'Hello, world!'
as one string
64. readlines() Returns a list of >>> sonnetFile = open(Path.home() /
strings, one string for 'sonnet29.txt')
each line of the file >>> sonnetFile.readlines()
O/P: [‘When, in disgrace with fortune
and men's eyes,\n', ---snip---- ‘And
look upon myself and curse my fate.']

65. . write() To write contents to a >>> baconFile = open('bacon.txt',


file 'w')
>>> baconFile.write('Hello,
world!\n')
O/P: 14

Saving Variables with the shelve Module


66. shelve.open('mydata') Opens a (shelf) file >>> import shelve
>>> shelfFile=shelve.open('mydata')
passed as argument
(=mydata)
67. shelffilename[variabl Returns content of >>> shelfFile['cats']
e] the variable. O/P: ['Zophie', 'Pooka', 'Simon']

variable holds some


content of file.
68. list(shelfFile.keys() Used to get values of >>> shelfFile =shelve.open('mydata')
>>> list(shelfFile.keys())
) the keys in list form. O/P: ['cats']

69. list(shelfFile.values Used to get values of >>> list(shelfFile.values())


()) the values in list form. O/P: [['Zophie', 'Pooka', 'Simon']]

3-28
Module-3: Manipulating Strings, Reading and Writing Files

70. shelfFile.close() Closes the shelf file >>> shelfFile.close()

71. pprint.pformat() Returns a string that >>> import pprint


>>> cats = [{'name': 'Zophie',
can be written to a .py 'desc': 'chubby'}, {'name':
file. 'Pooka', 'desc': 'fluffy'}]
>>> pprint.pformat(cats)
If the string from O/P: "[{'desc': 'chubby', 'name':
pprint.pformat() is 'Zophie'}, {'desc': 'fluffy',
saved to a .py file, the 'name': 'Pooka'}]"
file can be imported
as a module

3-29

You might also like