0% found this document useful (0 votes)
3 views86 pages

Module 3MYWRTTWYUKM

The document provides an overview of string manipulation in Python, covering topics such as string literals, escape characters, raw strings, multiline strings, and various string methods. It also discusses file handling, including reading and writing files, file paths, and the difference between absolute and relative paths. Additionally, it introduces the use of the pyperclip module for clipboard operations and concludes with a project example for a password locker.

Uploaded by

ktvinyas00
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)
3 views86 pages

Module 3MYWRTTWYUKM

The document provides an overview of string manipulation in Python, covering topics such as string literals, escape characters, raw strings, multiline strings, and various string methods. It also discusses file handling, including reading and writing files, file paths, and the difference between absolute and relative paths. Additionally, it introduces the use of the pyperclip module for clipboard operations and concludes with a project example for a password locker.

Uploaded by

ktvinyas00
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/ 86

SAPTHAGIRI COLLEGE OF

ENGINEERING
(Affiliated to Visvesvaraya Technological University, Belagavi & Approved by AICTE, New Delhi.)

Department of Information Science &


Engineering

Dept of ISE,SAPTHAGIRI COLLEGE OF ENGINEERING


1 March 2025 1
MANIPULATING STRINGS
Text is one of the most common forms of data your programs
will handle. You already know how to concatenate two string
values together with the + operator, but you can do much more
than that. You can extract partial strings from string values, add
or remove spacing, convert letters to lowercase or uppercase,
and check that strings are formatted correctly.

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 2


Working with Strings
String Literals:
• They begin and end with a single quote.
‘ Enter your name’
note:
'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.
( To solve this problem)

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.

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 3


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 consists of a backslash (\) followed by the character you want
to add to the string.

>>> print(‘ She said, "Thank you! It's mine “ ') >>> print('She said, \"Thank you! It\'s mine.\“ ')

SyntaxError: invalid syntax She said, "Thank you! It's mine."

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 4


Raw Strings:
You can place an r or 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.

>>> print(r'That is Carol\'s cat.') >>> print(R'That is Carol\'s cat.')


or

That is Carol\'s cat. That is Carol\'s cat.


>>> s = "Hello\tfrom AskPython\nHi"
>>> s = R"Hello\tfrom AskPython\nHi"
>>> print(s)
>>> print(s)
Hello from AskPython
Hello\tfrom AskPython\nHi
Hi
Raw strings are helpful if you are typing string values that contain many backslashes,

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 5


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.

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

Output:
Dear Alice,
Eve's cat has been arrested for catnapping, cat burglary, and extortion.
Sincerely,
Bob
1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 6
Without using multiline Strings with triple quotes
print('Dear Alice,\n\nEve\'s cat has been arrested for catnapping, cat burglary, and extortion.\n\nSincerely,\nBob')

Output:

Dear Alice,

Eve's cat has been arrested for catnapping, cat burglary, and extortion.

Sincerely,
Bob

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 7


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. The
following is perfectly valid Python code:
#This is a comment
#written in
#more than just one line
print("Hello, World!")

"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 8


Indexing and Slicing Strings
Strings use indexes and slices the same way lists do. You can think of the string 'Hello world!' as a list
and each character in the string as an item with a corresponding index.

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 9


Example: indexing and slicing string

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 10


The in and not in Operators with Strings

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 11


Useful String Methods
The upper(), lower(), isupper(), and islower() String Methods
i The upper() and lower() string methods return a new string where all the letters in the
original string have been converted to uppercase or lowercase, respectively.

How are you?


GREat
I feel great too.
1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 12
The isupper() and islower() 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 Manipulating Strings 129
lowercase, respectively. Otherwise, the method returns False.

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 13


# Python isupper() method example
str = "WELCOME TO JAVATPOINT"
str2 = str.isupper()
print(str2)
Output:
True
False
True
str3 = "WELCOME To JAVATPOINT."
str4 = str3.isupper()
print(str4)

str5 = "123 @#$ -JAVA."


str6 = str5.isupper()
print(str6)

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 14


The isX String Methods
Here are some common isX 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.
• 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.

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 15


example

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 16


The isX string methods are helpful when you need to validate user input
Write a program repeatedly asks users for their age and a password until they provide
valid input

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 17


The startswith() and endswith() String Methods
The startswith() and endswith() methods return True if the string value they are called
on begins or ends (respectively) with the string passed to the method; otherwise, they
return False.

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 18


The join() and split() String Methods
The join() method is useful when you have a list of strings that need to be joined together
into a single string value. The join() method is called on a string, gets passed a list of
strings, and returns a string. list1 = ['1','2','3','4']

s = "-"

s = s.join(list1)

print(s)

1-2-3-4

Notice that the string join() calls on is inserted between each string of the list argument.

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 19


The split() method
The split() method does the opposite: It’s called on a string value and returns a list
of strings. Enter the following into the interactive shell:

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 20


example

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 21


Justifying Text with rjust(), ljust(), and center()
The rjust() and ljust() string methods return a padded version of the string they are
called on, with spaces inserted to justify the text. The first argument to both methods
is an integer length for the justified string.

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 22


Write a program to print tabular data that has the correct spacing.
def printPicnic(itemsDict, leftWidth, rightWidth):
print('PICNIC ITEMS'.center(leftWidth + rightWidth, '-'))
---PICNIC ITEMS--
for k, v in itemsDict.items(): sandwiches.. 4
print(k.ljust(leftWidth, '.') + str(v).rjust(rightWidth)) apples...... 12
cups........ 4
cookies..... 8000
-------PICNIC ITEMS-------
picnicItems = {'sandwiches': 4, 'apples': 12, 'cups': 4, 'cookies': 8000} sandwiches.......... 4
apples.............. 12
cups................ 4
printPicnic(picnicItems, 12, 5) cookies............. 8000
printPicnic(picnicItems, 20, 6)

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 23


Removing Whitespace with strip(), rstrip(), and lstrip()
Sometimes you may want to strip off whitespace characters (space, tab, and newline) from
the left side, right side, or both sides of a string. The strip() string method will return a new
string without any whitespace characters at the beginning or end.
Optionally, a string argument will specify which characters on
the ends should be stripped.

The order of the characters in the string passed to strip() does


not matter: strip('ampS') will do the same thing as strip('mapS')
or strip('Spam').
1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 24
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 your computer’s clipboard. Sending the output of your program to the clipboard will
make it easy to paste it to an email, word processor, or some other software.

note
Pyperclip does not come with
Python. To install it, follow the
directions for installing third-party
modules in Appendix A. After
installing the pyperclip module,

pip install pyperclip

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 25


Project: Password Locker
You probably have accounts on many different websites. It’s a bad habit to use the
same password for each of them because if any of those sites has a security breach,
the hackers will learn the password to all of your other accounts. It’s best to use
password manager software on your computer that uses one master password to
unlock the password manager.

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 26


passwordproj.py
import pyperclip
PASSWORDS = {'email': 'F7minlBDDuvMJuxESSKHFhTxFtjVB6',
'blog': 'VmALvQyKAxiVH5G8v01if1MLZF3sdt',
'luggage': '12345'}
import sys
if len(sys.argv) < 2:
print('Usage: python pw.py [account] - copy account password')
sys.exit()
account = sys.argv[1] # first command line arg is the account name
if account in PASSWORDS:
pyperclip.copy(PASSWORDS[account])
print('Password for ' + account + ' copied to clipboard.')
else:
print('There is no account named ' + account)

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 27


Module-3 chapter -2
Reading and Writing Files
Variables are a fine way to store data while your program is running,
but if you want your data to persist even after your program has
finished, you need to save it to a file. You can think of a file’s
contents as a single string value, potentially gigabytes in size. In this
chapter, you will learn how to use Python to create, read, and save
files on the hard drive

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 29


Files and File Paths
A file has two key properties: a filename (usually written as one word) and a path. The
path specifies the location of a file on the computer

C:\Users\asweigart\Documents\project.docx

path
fileName

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 30


Backslash on Windows and Forward Slash on OS X and 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.
Fortunately, this is simple to do with the os.path.join() function. If you pass it the
string values of individual file and folder names in your path, os path join() will return
a string with a file path using the correct path separators.

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 31


For example, the following example joins names from a list of filenames to the
end of a folder’s name:
import os
myFiles = ['accounts.txt', 'details.csv', 'invite.docx']
for filename in myFiles:
print(os.path.join('C:\\Users\\asweigart', filename))

Output:

C:\Users\asweigart\accounts.txt
C:\Users\asweigart\details.csv
C:\Users\asweigart\invite.docx

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 32


The Current Working Directory
Every program that runs on your computer has a current working directory, or cwd
Any filenames or paths that do not begin with the root folder are assumed to be
under the current working directory
For example:
You can get the current working directory as a string value with the os getcwd()
function and change it with os chdir()

import os
import os
os.chdir('C:\\Windows\\System32')
print(os.getcwd()) print(os.getcwd())
Output: Output:

C:\Users\Admin\.spyder-py3 C:\Windows\System32

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 33


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

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 34


Absolute vs Relative
There are two ways to specify a file path.
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. These are not real folders but special
names that can be used in a path.
A single period (“dot”) for a folder name is shorthand for “this directory ”
Two periods (“dot-dot”) means “the parent folder ”

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 35


an example of some folders and files. When the current working directory is set
to C:\bacon, the relative paths for the other folders and files are set as they are
in the figure.

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 36


Creating New Folders with os makedirs()
Your programs can create new folders (directories) with the os.makedirs() function.
Enter the following into the interactive shell:

import os
os.makedirs('C:\\delicious\\walnut\\waffles')

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 37


The os path Module
The os.path module contains many helpful functions related to filenames and file paths.
For instance, you’ve already used os path join() to build paths in a way that will work
on any operating system
Handling Absolute and Relative Paths
The os.path module provides functions for returning the absolute path of a relative path
and for checking whether a given path is an absolute path.
• 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.
1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 38
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.
import os Output:
print(os.path.abspath('.')) C:\Users\Admin\.spyder-py3

Calling os.path.isabs(path) will return True if the argument is an absolute path and
False if it is a relative path.
import os
import os
print( os.path.isabs('C:\\Users\\Admin\\.spyder-py3'))
print( os.path.isabs('.'))
Output:
output
True
False
1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 39
Enter the following calls to os path relpath() into the interactive shell:
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.

import os
print(os.path.relpath('C:\\Windows', 'C:\\'))

Output:
Windows

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 40


os path dirname(path) and os path basename(path)
Calling os path dirname(path) will return a string of everything that comes before the last
slash in the path argument. Calling os path basename(path) will return a string of
everything that comes after the last slash in the path argument.

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 41


If you need a path’s dir name and base name together, you can just call
os path split() to get a tuple value with these two strings, like so:

Notice that you could create the same tuple by calling os.path.dirname() and
os.path.basename() and placing their return values in a tuple.

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 42


os.path.sep:
>>> calcFilePath =
'C:\\Windows\\System32\\calc.exe'
>>> calcFilePath.split(os.path.sep)
['C:', 'Windows', 'System32', 'calc.exe']

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 43


Finding File Sizes and Folder Contents
Once you have ways of handling file paths, you can then start gathering information
about specific files and folders The os.path module provides functions for
finding the size of a file in bytes and the files and folders inside a given
folder.
• 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.)

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 44


As you can see, the calc.exe program on my computer is 776,192 bytes
in size,

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 45


example
I have a lot of files in C:\Windows\system32. If I want to find the total size
of all the files in this directory, I can use os path getsize() and os listdir()
together

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 46


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.

• Calling os path exists(path) will return True if the file or folder referred to in the
argument exists and will return False if it does not exist.
• Calling os path isfile(path) will return True if the path argument exists and is a file
and will return False otherwise.
• Calling os path isdir(path) will return True if the path argument exists and is a folder
and will return False otherwise.

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 47


1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 48
The File Reading/Writing Process
Once you are comfortable working with folders and relative paths, you’ll be
able to specify the location of files to read and write. The functions covered
in the next few sections will apply to plaintext files. Plaintext files Reading
and Writing 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 OS X’s TextEdit


application. Your programs can easily read the contents of plaintext files and
treat them as an ordinary string value.

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 49


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, like in Figure

Since every different type of binary file must


be handled in its own way, this book will not
go into reading and writing raw binary files
directly. Fortunately, many modules make
working with binary files easier—you will
explore one of them, the shelve module,
later in this chapter.

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 50


Three steps to reading or writing files
There are three steps to reading or writing files in Python.
1. Call the open() function to return a File object.
2. Call the read() or write() method on the File object.
3. Close the file by calling the close() method on the File object.

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 51


Opening Files with the open() Function
To open a file with the open() function, you pass it a string path indicating the file you
want to open; it can be either an absolute or relative path. The open() function
returns a File object.

Try it by creating a text file named hello.txt using Notepad or TextEdit. Type Hello
world! as the content of this text file and save it in your user home folder.

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 52


Reading the Contents of Files
Now that you have a File object, you can start reading from it. If you want to read the
entire contents of a file as a string value, use the File object’s read() method.
helloFile =
open('C:\\Users\\TEST\\first.txt','r')
helloread = helloFile.read() first.txt
print(helloread)

output

SAPTHAGIRI COLLEGE OF ENGINEERING


INFORMATION SCIENCE AND ENGINEERING

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 53


the readlines() method
you can use the readlines() method to get a list of string values from the file, one string
for each line of text.
helloFile = open('C:\\Users\\TEST\\second txt','r')
helloread = helloFile readlines()
print(helloread) second.txt

output
["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,']

Note that each of the string values ends with a newline


character, \n , except for the last line of the file. A list of strings
is often easier to work with than a single large string value.
1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 54
Writing to Files
Python allows you to write content to a file in a way similar to how the print()
function “writes” strings to the screen.
There are two way can write the data to a file
1. Write mode
2. Append mode

Write mode:
Write mode will overwrite the existing file and start from scratch, just like when you
overwrite a variable’s value with a new value. Pass 'w' as the second argument to
open() to open the file in write mode

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 55


Example:
Note:
If the filename passed to open() does not exist, both write and append mode will
create a new, blank file. Bacon.txt

baconFile = open('C:\\Users\\TEST\\bacon.txt', 'w')


baconFile.write('MY NAME IS SUDARSANAN\n')
baconFile.close()

readname = open('C:\\Users\\TEST\\bacon.txt','r')
helloread = readname.read()
print(helloread)

output
MY NAME IS SUDARSANAN

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 56


Example2 once again write a new data to bacon.txt file
baconFile = open('C:\\Users\\TEST\\bacon.txt', 'w')
baconFile.write('WHAT IS YOUR NAME\n')
baconFile.close() bacon.txt
readname = open('C:\\Users\\TEST\\bacon.txt','r')
helloread = readname.read()
print(helloread)

output
WHAT IS YOUR NAME

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 57


Append mode:
Append mode, on the other hand, will append text to the end of the existing file. You can think of this as appending to a list
in a variable, rather than overwriting the variable altogether. Pass 'a' as the second argument to open() to open the file in
append mode.

baconFile = open('C:\\Users\\TEST\\bacon.txt', 'a') bacon.txt


baconFile.write('MY NAME IS SUDARSANAN\n')
baconFile.close()
readname = open('C:\\Users\\TEST\\bacon.txt','r')
helloread = readname.read()
print(helloread)

Output:

WHAT IS YOUR NAME


MY NAME IS SUDARSANAN

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 58


Saving Variables with the shelve Module
• You can save variables in your Python programs to binary shelf files using
the shelve module.
• The shelve module in Python’s standard library is a simple yet effective
tool for persistent data storage when using a relational database
solution is not required. The shelf object defined in this module is
dictionary-like object which is persistently stored in a disk file.

• Only string data type can be used as key in this special dictionary object
• After running the code on Windows, you will see three new files in the
current working directory: mydata bak, mydata dat, and mydata dir

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 59


The shelve module defines three classes as follows −

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 60


Create shelf object:

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 61


Example: store the data in shelfobject
import shelve
s = shelve.open("test")
s['name'] = "Ajay"
s['age'] = 23
s['marks'] = 75
s.close()

This will create test dir,


test bak, test dat file in
current directory and
store key-value data in
hashed form
1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 62
To access value of a particular key in shelf.
import shelve
s=shelve.open('test')
print( s['age'])
s['age']=25
print(s.get('age'))

output

23
25

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 63


The Shelf object has following methods available

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 64


The items(), keys() and values() methods return view objects

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 65


To remove a key-value pair from shelf

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 66


To merge items of another dictionary with shelf use update() method

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 67


Example:
import shelve
shelfFile = shelve.open('mydata')
cats = ['Zophie', 'Pooka', 'Simon']
output
shelfFile[‘cats'] = cats
shelfFile.close() ['Zophie', 'Pooka', 'Simon']

shelfFile = shelve.open('mydata')
print(shelfFile[‘cats'])
shelfFile.close()

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 68


Accessing key and value using list function

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 69


pprint() function (pretty print)
from pprint import pprint output
data = [
PRINT:
(1, {'a': 'A', 'b': 'B', 'c': 'C', 'd': 'D'}),
[(1, {'a': 'A', 'b': 'B', 'c': 'C', 'd': 'D'}), (3, ['m', 'n'])]
(3, ['m', 'n']),
PPRINT:
]
[(1,
print('PRINT:')
{'a': 'A',
print(data)
'b': 'B',
print()
'c': 'C',
print('PPRINT:')
'd': 'D'}),
pprint(data,width='6')
(3,
['m',
'n'])]

Recall from “Pretty Printing” that the pprint.pprint() function will “pretty print” the contents of a list or dictionary to
the screen

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 70


Saving Variables with the pprint pformat() Function
The pprint.pformat() function will return this same text as a string instead of printing it.
Not only is this string formatted to be easy to read, but it is also syntactically correct
Python code. Say 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 .py file.

import pprint
cats = [{'name': 'Zophie', 'desc': 'chubby'}, {'name': 'Pooka', 'desc': 'fluffy'}]
pprint.pformat(cats)
fileObj = open('myCats.py', 'w')
fileObj.write('cats = ' + pprint.pformat(cats) + '\n')
fileObj.close()

cats = [{'desc': 'chubby', 'name': 'Zophie'}, {'desc': 'fluffy', 'name': 'Pooka'}] myCats.py

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 71


And since Python scripts are themselves just text files with the .py file extension,
your Python programs can even generate other Python programs. You can then
import these files into scripts.
import myCats
print(myCats.cats)
print(myCats.cats[0])
print(myCats.cats[0]['name'])

Output:

[{'desc': 'chubby', 'name': 'Zophie'}, {'desc': 'fluffy', 'name': 'Pooka'}]

{'desc': 'chubby', 'name': 'Zophie'}

Zophie
1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 72
Project: Generating Random Quiz Files
Say you’re a geography teacher with 35 students in your class and you want to give a
pop quiz on US state capitals.

Here is what the program does:


• Creates 35 different quizzes.
• Creates 50 multiple-choice questions for each quiz, in random order.
• Provides the correct answer and three random wrong answers for each question, in random order.
• Writes the quizzes to 35 text files.
• Writes the answer keys to 35 text files.
This means the code will need to do the following:
• Store the states and their capitals in a dictionary.
• Call open(), write(), and close() for the quiz and answer key text files.
• Use random.shuffle() to randomize the order of the questions and multiple-choice options.

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 73


Step 1: Store the Quiz Data in a Dictionary

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 74


Step 2: Create the Quiz File and Shuffle the Question Order
The code in the loop will be repeated for quizNum in range(35): # Generate 35 quiz files.
35 times—once for each quiz— so # Create the quiz and answer key files
you have to worry about only one quizFile = open('capitalsquiz%s.txt' % (quizNum + 1), 'w')
quiz at a time within the loop. First answerKeyFile = open('capitalsquiz_answers%s.txt' % (quizNum + 1), 'w')
you’ll create the actual quiz file. It
needs to have a unique filename and
should also have some kind of # Write out the header for the quiz
standard header in it, with places for quizFile.write('Name:\n\nDate:\n\nPeriod:\n\n')
the student to fill in a name, date, quizFile.write((' ' * 20) + 'State Capitals Quiz (Form %s)' % (quizNum +
and class period. Then you’ll need to 1))
get a list of states in randomized quizFile.write('\n\n')
order, which can be used later to
create the questions and answers for # Shuffle the order of the states
the quiz. states = list(capitals.keys()) # get all states in a list
random.shuffle(states) # randomize the order of the states

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 75


Captitalsquiz1.txt

states
['Maryland', 'Michigan', 'Alabama', 'Wisconsin', 'Vermont', 'North Carolina', 'Nebraska', 'Rhode Island', 'Colorado', 'Texas',
'Oregon', 'Tennessee', 'Delaware', 'North Dakota', 'Idaho', 'New Mexico', 'Mississippi', 'Ohio', 'New Jersey', 'Connecticut', 'West
Virginia', 'Illinois', 'California', 'South Dakota', 'Florida', 'Arizona', 'Maine', 'Missouri', 'Alaska', 'New York', 'Minnesota',
'Georgia', 'Montana', 'Louisiana', 'New Hampshire', 'Hawaii', 'South Carolina', 'Indiana', 'Virginia', 'Utah', 'Wyoming',
'Massachusetts', 'Arkansas', 'Nevada', 'Pennsylvania', 'Oklahoma', 'Kentucky', 'Iowa', 'Washington', 'Kansas']
['Arizona', 'Kansas', 'West Virginia', 'South Carolina', 'Wisconsin', 'Alabama', 'Connecticut', 'Washington', 'Maine', 'Wyoming',
'New York', 'Alaska', 'New Hampshire', 'Missouri', 'Minnesota', 'Arkansas', 'Maryland', 'Oklahoma', 'Illinois', 'New Mexico', 'New
Jersey', 'North Carolina', 'Colorado', 'Indiana', 'Ohio', 'Mississippi', 'Idaho', 'Montana', 'Nebraska', 'Kentucky', 'Utah', 'Oregon',
'California', 'Iowa', 'Florida', 'Michigan', 'Nevada', 'Georgia', 'Pennsylvania', 'North Dakota', 'Louisiana', 'Massachusetts',
'Tennessee', 'Hawaii', 'Texas', 'Vermont', 'South Dakota', 'Delaware', 'Virginia', 'Rhode Island']

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 76


Step 3: Create the Answer Options
Now you need to generate the
answer options for each
question, which will be
multiple choice from A to D.
You’ll need to create another
for loop—this one to generate
the content for each of the 50
questions on the quiz. Then
there will be a third for loop
nested inside to generate the
multiple-choice options for
each question. Make your code 1. This loop will loop through the states in the shuffled states list, from states[0] to
look like the following: states[49], find each state in capitals, and store that state’s corresponding capital in
correctAnswer.
2. The list of possible wrong answers is trickier. You can get it by duplicating all the values
in the capitals dictionary
3. deleting the correct answer
4. selecting three random values from this list

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 77


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

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 78


File name: Capitalsquiz1 txt

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 79


Filename: capitalsquiz_answers1.txt

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 80


Project: Multiclipboard
Say you have the boring task of filling out many forms in a web page
or software with several text fields. The clipboard saves you from
typing the same text over and over again. But only one thing can be
on the clipboard at a time. If you have several different pieces of text
that you need to copy and paste, you have to keep highlighting and
copying the same few things over and over again.

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 81


The program will save each piece of clipboard text under a
keyword. For example, when you run py mcb pyw save spam,
the current contents of the clipboard will be saved with the
keyword spam. This text can later be loaded to the clipboard
again by running py mcb pyw spam. And if the user forgets what
keywords they have, they can run py mcb pyw list to copy a list
of all keywords to the clipboard.

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 82


Here’s what the program does:
• The command line argument for the keyword is checked.
• If the argument is save, then the clipboard contents are saved to the
keyword
• If the argument is list, then all the keywords are copied to the
clipboard.
• Otherwise, the text for the keyword is copied to the keyboard.
This means the code will need to do the following:
• Read the command line arguments from sys argv
• Read and write to the clipboard.
• Save and load to a shelf file.

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 83


Step 1: Comments and Shelf Setup

s v. Copying and pasting will require the pyperclip module, and reading the command line arguments will require the sys
module The shelve module will also come in handy: Whenever the user wants to save a new piece of clipboard text, you’ll
save it to a shelf file. Then, when the user wants to paste the text back to their clipboard, you’ll open the shelf file and load it
back into your program. The shelf file will be named with the prefix mcb w.

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 84


Step 2: Save Clipboard Content with a Keyword
The program does different things depending on whether the user wants to save text
to a keyword, load text into the clipboard, or list all the existing keywords.

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 85


Step 3: List Keywords and Load a Keyword’s Content

1 March 2025 Dept of ISE SAPTHAGIRI COLLEGE OF ENGINEERING 86

You might also like