0% found this document useful (0 votes)
4 views30 pages

Python M 3

Chapter 3 of the Python module covers string manipulation, including string literals, methods, and projects like a password locker and adding bullets to wiki markup. It explains various string methods such as indexing, slicing, and modifying strings using functions like upper(), lower(), join(), and split(). Additionally, it discusses practical applications, including handling command line arguments and using the pyperclip module for clipboard operations.

Uploaded by

talwarisiri0703
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)
4 views30 pages

Python M 3

Chapter 3 of the Python module covers string manipulation, including string literals, methods, and projects like a password locker and adding bullets to wiki markup. It explains various string methods such as indexing, slicing, and modifying strings using functions like upper(), lower(), join(), and split(). Additionally, it discusses practical applications, including handling command line arguments and using the pyperclip module for clipboard operations.

Uploaded by

talwarisiri0703
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/ 30

Module 3 Python

CHAPTER 3: MANIPULATING STRINGS

1. Working with Strings


2. Useful String Methods
3. Project: Password Locker
4. Project: Adding Bullets to Wiki Markup
3.1 Working with strings String
Literals
String values begin and end with a single quote.
But we want to use either double or single quotes within a string then we have a multiple ways to doit as
shown below.
Double Quotes
 One benefit of using double quotes is that the string can have a single quote character in it.

 Since the string begins with a double quote, Python knows that the single quote is part of thestring
and not marking the end of the string.
Escape Characters
 If you need to use both single quotes and double quotes in the string, you’ll need to use escape
characters.
 An escape character consists of a backslash (\) followed by the character you want to add to thestring.
 Python knows that the single quote in Bob\'s has a backslash, it is not a single quote meant to end the

string value. The escape characters \' and \" allows to put single quotes and double quotes inside your
strings, respectively.

 Ex:

 The different special escape characters can be used in a program as listed below in a table.

Tejaswini S, Assistant Professor, Dept. of AD, CIT, Gubbi


1
Module 3 Python
Raw Strings
 You can place an r before the beginning quotation mark of a string to make it a raw string. A raw string
completely ignores all escape characters and prints any backslash that appears in the string.

Multiline Strings with Triple Quotes


 A multiline string in Python begins and ends with either three single quotes or three doublequotes.
 Any quotes, tabs, or newlines in between the “triple quotes” are considered part of the string.
Program

Output

 The following print() call would print identical text but doesn’t use a multiline string.

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.

Indexing and Slicing Strings


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

Tejaswini S, Assistant Professor, Dept. of AD, CIT, Gubbi


2
Module 3 Python
The space and exclamation point are included in the character count, so 'Hello world!' is 12
characters long.
If we specify an index, you’ll get the character at that position in the string.

If we specify a range from one index to another, the starting index is included and the ending index is not.

The substring we get from spam[0:5] will include everything from spam[0] to spam[4], leaving outthe
space at index 5.
Note: slicing a string does not modify the original string.
The in and not in Operators with Strings
The in and not in operators can be used with strings just like with list values.
An expression with two strings joined using in or not in will evaluate to a Boolean True or False.

These expressions test whether the first string (the exact string, case sensitive) can be found withinthe
second string.
3.2 Useful String Methods
Several string methods analyze strings or create transformed string values.
The upper(), lower(), isupper(), and islower() String Methods
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.

Tejaswini S, Assistant Professor, Dept. of AD, CIT, Gubbi


3
Module 3 Python
These methods do not change the string itself but return new string values.
If we want to change the original string, we have to call upper() or lower() on the string and thenassign
the new string to the variable where the original was stored.
The upper() and lower() methods are helpful if we need to make a case-insensitive comparison.
In the following small program, it does not matter whether the user types Great, GREAT, or
grEAT, because the string is first converted to lowercase.

Program Output
The isupper() and islower() methods will return a Boolean True value if the string has at least one letter and
all the letters are uppercase or lowercase, respectively. Otherwise, the method returns False.
Since the upper() and lower() string methods themselves return strings, you can call string methods on those
returned string values as well. Expressions that do this will look like a chain of method calls.

The isX String Methods


There are several string methods that have names beginning with the word is. These methods returna
Boolean value that describes the nature of the string.
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 notblank.

Tejaswini S, Assistant Professor, Dept. of AD, CIT, Gubbi


4
Module 3 Python
 istitle() returns True if the string consists only of words that begin with an uppercase letter
followed by only lowercase letters.

The isX string methods are helpful when you need to validate user input.
For example, the following program repeatedly asks users for their age and a password until they
provide valid input.

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

These methods are useful alternatives to the == equals operator if we need to check only whether the
first or last part of the string, rather than the whole thing, is equal to another string.

Tejaswini S, Assistant Professor, Dept. of AD, CIT, Gubbi


5
Module 3 Python
The join() and split() String Methods
Join()
The join() method is useful when we have a list of strings that need to be joined together into asingle
string value.
The join() method is called on a string, gets passed a list of strings, and returns a string. The
returned string is the concatenation of each string in the passed-in list.

string join() calls on is inserted between each string of the list argument.
o Ex: when join(['cats', 'rats', 'bats']) is called on the ', ' string, the returned string is 'cats, rats,bats'.
o join() is called on a string value and is passed a list value.
Split()
The split() method is called on a string value and returns a list of strings.

We can pass a delimiter string to the split() method to specify a different string to split upon.

A common use of split() is to split a multiline string along the newline characters.

Passing split() the argument '\n' lets us split the multiline string stored in spam along the newlinesand
return a list in which each item corresponds to one line of the string.
Justifying Text with rjust(), ljust(), and center()
The rjust() and ljust() string methods return a padded version of the string they are called on, withspaces
inserted to justify the text.

Tejaswini S, Assistant Professor, Dept. of AD, CIT, Gubbi


6
Module 3 Python
The first argument to both methods is an integer length for the justified string.

'Hello'.rjust(10) says that we want to right-justify 'Hello' in a string of total length 10. 'Hello' is five
characters, so five spaces will be added to its left, giving us a string of 10 characters with 'Hello' justified
right.
An optional second argument to rjust() and ljust() will specify a fill character other than a space character.

The center() string method works like ljust() and rjust() but centers the text rather than justifying it to the
left or right.

These methods are especially useful when you need to print tabular data that has the correct
spacing.
In the below program, we define a printPicnic() method that will take in a dictionary of informationand use
center(), ljust(), and rjust() to display that information in a neatly aligned table-like format.
o The dictionary that we’ll pass to printPicnic() is picnicItems.
o In picnicItems, we have 4 sandwiches, 12 apples, 4 cups, and 8000 cookies. We want to
organize this information into two columns, with the name of the item on the left and the
quantity on the right.

Program output

Tejaswini S, Assistant Professor, Dept. of AD, CIT, Gubbi


7
Module 3 Python
Removing Whitespace with strip(), rstrip(), and lstrip()
The strip() string method will return a new string without any whitespace characters at the
beginning or end.
The lstrip() and rstrip() methods will remove whitespace characters from the left and right ends,
respectively.

Optionally, a string argument will specify which characters on the ends should be stripped.

strip() the argument 'ampS' will tell it to strip occurences of a, m, p, and capital S from the ends of
Passing
the string stored in spam.
The order of the characters in the string passed to strip() does not matter: strip('ampS') will do thesame
thing as strip('mapS') or strip('Spam').
Copying and Pasting Strings with the pyperclip Module
The pyperclip module has copy() and paste() functions that can send text to and receive text fromyour
computer’s clipboard.

Of course, if something outside of your program changes the clipboard contents, the paste()
function will return it.

3.3 Project: Password Locker


We 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 tounlock
the password manager.
Then you can copy any account password to the clipboard and paste it into the website’s Passwordfield
The password manager program you’ll create in this example isn’t secure, but it offers a basic
demonstration of how such programs work.

Tejaswini S, Assistant Professor, Dept. of AD, CIT, Gubbi


8
Module 3 Python
Step 1: Program Design and Data Structures
We have to run this program with a command line argument that is the account’s name--for instance, email
or blog. That account’s password will be copied to the clipboard so that the user can paste it into a Password
field. The user can have long, complicated passwords without having to memorize them.
We need to start the program with a #! (shebang) line and should also write a comment that briefly describes
the program. Since we want to associate each account’s name with its password, we can store these as strings
in a dictionary.

Step 2: Handle Command Line Arguments


The command line arguments will be stored in the variable sys.argv.
The first item in the sys.argv list should always be a string containing the program’s filename
('pw.py'), and the second item should be the first command line argument.

Step 3: Copy the Right Password


The account name is stored as a string in the variable account, you need to see whether it exists in the
PASSWORDS dictionary as a key. If so, you want to copy the key’s value to the clipboard using
pyperclip.copy().

This new code looks in the PASSWORDS dictionary for the account name. If the account name is a key in
the dictionary, we get the value corresponding to that key, copy it to the clipboard, and printa message
saying that we copied the value. Otherwise, we print a message saying there’s no account with that name.

Tejaswini S, Assistant Professor, Dept. of AD, CIT, Gubbi


9
Module 3 Python

On Windows, you can create a batch file to run this program with the win-R Run window. Type the following
into the file editor and save the file as pw.bat in the C:\Windows folder:

With this batch file created, running the password-safe program on Windows is just a matter of pressing win-
R and typing pw <account name>.

3.4 Project: Adding Bullets to Wiki Markup


When editing a Wikipedia article, we can create a bulleted list by putting each list item on its own line and
placing a star in front.
But say we have a really large list that we want to add bullet points to. We could just type those stars at the
beginning of each line, one by one. Or we could automate this task with a short Python script.
The bulletPointAdder.py script will get the text from the clipboard, add a star and space to the beginning of
each line, and then paste this new text to the clipboard.
Ex:

Program output
Step 1: Copy and Paste from the Clipboard
You want the bulletPointAdder.py program to do the following:
1. Paste text from the clipboard
2. Do something to it
3. Copy the new text to the clipboard
Steps 1 and 3 are pretty straightforward and involve the pyperclip.copy() and pyperclip.paste()
functions. saving the following program as bulletPointAdder.py:

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


The call to pyperclip.paste() returns all the text on the clipboard as one big string. If we used the “List of
Lists of Lists” example, the string stored in text.
The \n newline characters in this string cause it to be displayed with multiple lines when it is printed or

Tejaswini S, Assistant Professor, Dept. of AD, CIT, Gubbi


10
Module 3 Python
pasted from the clipboard.
We could write code that searches for each \n newline character in the string and then adds the star just after
that. But it would be easier to use the split() method to return a list of strings, one for each line in the original
string, and then add the star to the front of each string in the list.

We split the text along its newlines to get a list in which each item is one line of the text. For eachline,
we add a star and a space to the start of the line. Now each string in lines begins with a star.
Step 3: Join the Modified Lines
The lines list now contains modified lines that start with stars.
pyperclip.copy() is expecting a single string value, not a list of string values. To make this singlestring
value, pass lines into the join() method to get a single string joined from the list’s strings.

When this program is run, it replaces the text on the clipboard with text that has stars at the start of each line.

Tejaswini S, Assistant Professor, Dept. of AD, CIT, Gubbi


11
Module 3 Python
MODULE 3:
CHAPTER 8: READING AND WRITING FILES
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. For example, there is a file on my Windows 7 laptop with the filename
projects.docx in the path C:\Users\asweigart\Documents. The part of the filename after the last period is
called the file’s extension and tells you a file’s type. project.docx is a Word document, and Users, asweigart,
and Documents all refer to folders (also called directories). Folders can contain files and other folders. For
example, project.docx is in the Documents folder, which is inside the asweigart folder, which is inside the
Users folder. Figure 8-1 shows this folder organization.

The C:\ part of the path is the root folder, which contains all other folders. On Windows, the root folder is
named C:\ and is also called the C: drive. On OS X and Linux, the root folder is /.

Additional volumes, such as a DVD drive or USB thumb drive, will appear differently on different operating
systems. On Windows, they appear as new, lettered root drives, such as D:\ or E:\. On OS X, they appear as
new folders under the /Volumes folder. On Linux, they appear as new folders under the /mnt (“mount”) folder.
Also note that while folder names and filenames are not case sensitive on Windows and OS X, they are case
sensitive on Linux.

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. If you want your programs to work on all operating
systems, you will have to write your Python scripts to handle both cases.

We can do this by using 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.

Tejaswini S, Assistant Professor, Dept. of AD, CIT, Gubbi


12
Module 3 Python

After running the above program on Windows, so os.path .join('usr', 'bin', 'spam') returned 'usr\\bin\\spam'.

(Notice that the backslashes are doubled because each backslash needs to be escaped by another
backslash character.) If I had called this function on OS X or Linux, the string would have been
'usr/bin/spam'.
The os.path.join() function is helpful if you need to create strings for filenames.

Below example joins names from a list of filenames to the end of a folder’s name:

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. You can get the
current working directory as a string value with the os.getcwd() function and change it with os.chdir().

Here, the current working directory is set to C:\Python34, so the filename project.docx refers to
C:\Python34\project.docx. When we change the current working directory to C:\Windows, project.docx is
interpreted as C:\ Windows\project.docx.

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

Note: While folder is the more modern name for directory, note that current working directory (or just
working directory) is the standard term, not current working folder.

Tejaswini S, Assistant Professor, Dept. of AD, CIT, Gubbi


13
Module 3 Python
Absolute vs. Relative Paths
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 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.”

Figure 8-2 is 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.

Note: The .\ at the start of a relative path is optional. For example, .\spam.txt and spam.txt refer to the same
file.

Creating New Folders with os.makedirs()

With the os.makedirs() function we can create new folders(directories)

This will create not just the C:\delicious folder but also a walnut folder inside C:\delicious and a waffles folder
inside C:\delicious\walnut. That is, os.makedirs() will create any necessary intermediate folders in order to
ensure that the full path exists. Figure 8-3 shows this hierarchy of folders.

Tejaswini S, Assistant Professor, Dept. of AD, CIT, Gubbi


14
Module 3 Python

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. Since os.path is a
module inside the os module, you can import it by simply running import os. Whenever your programs need
to work with files, folders, or file paths, you can refer to the short examples in this section. The full
documentation for the os.path module is on the Python website at http://docs.python.org/3/
library/os.path.html.

Note: Most of the examples that are used in this section will require the os module, so remember to import it
at the beginning of any script you write and any time you restart IDLE. Otherwise, you’ll get a NameError:
name 'os' is not defined error message.

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.

Since C:\Python34 was the working directory when os.path.abspath() was called, the “single-dot” folder
represents the absolute path 'C:\\Python34'.

Tejaswini S, Assistant Professor, Dept. of AD, CIT, Gubbi


15
Module 3 Python
Enter the following calls to os.path.relpath() into the interactive shell:

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. The dir name and base name of a path are outlined in Figure 8-4.

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.

But os.path.split() is a nice shortcut if you need both values.

Tejaswini S, Assistant Professor, Dept. of AD, CIT, Gubbi


16
Module 3 Python
Also, note that os.path.split() does not take a file path and return a list of strings of each folder. For that, use
the split() string method and split on the string in os.sep. Recall from earlier that the os.sep variable is set to
the correct folder-separating slash for the computer running the program.

For example, enter the following into the interactive shell:

On OS X and Linux systems, there will be a blank string at the start of the returned list:

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

Finding File Sizes and Folder Contents


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

The calc.exe program on my computer is 776,192 bytes in size.

The above program finds the total size of all the files in C:\Windows\system32 directory.

As we loop over each filename in the C:\Windows\System32 folder, the totalSize variable is incremented by
the size of each file. Notice how when we call os.path.getsize(), we use os.path.join() to join the folder name
with the current filename. The integer that os.path.getsize() returns is added to the value of totalSize. After
looping through all the files, we print totalSize to see the total size of the C:\Windows\System32 folder.

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.

Tejaswini S, Assistant Professor, Dept. of AD, CIT, Gubbi


17
Module 3 Python
• 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.

You can determine whether there is a DVD or flash drive currently attached to the computer by checking for it with the
os.path.exists() function. For instance, if we want to check for a flash drive with the volume named D:\ on Windows computer,
we could do that with the following:

Oops! It looks like I forgot to plug in my flash drive.

The File Reading/Writing Process


Plaintext files contain only basic text characters and do not include font, size, or color information. Text files
with the .txt extension or Python script files with the .py extension are examples of plaintext files. These can
be opened with Windows’s Notepad or OS X’s TextEdit application. Your programs can easily read the
contents of plaintext files and treat them as an ordinary string value.
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 8-5.

Tejaswini S, Assistant Professor, Dept. of AD, CIT, Gubbi


18
Module 3 Python
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.

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.

Create 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. Then, on Window OS, enter the following into the
interactive shell:

On Mac OS,

Make sure to replace your_home_folder with your computer username. For example, my username is
asweigart, so I’d enter 'C:\\Users\\asweigart\\ hello.txt' on Windows.

Both these commands will open the file in “reading plaintext” mode, or read mode for short. 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.
Read mode is the default mode for files you open in Python. But if you don’t want to rely on Python’s
defaults, you can explicitly specify the mode by passing the string value 'r' as a second argument to open(). So
open('/Users/asweigart/ hello.txt', 'r') and open('/Users/asweigart/hello.txt') do the same thing.

The call to open() returns a File object. A File object represents a file on your computer; it is simply another
type of value in Python, much like the lists and dictionaries.

Reading the Contents of Files


To read the entire contents of a file as a string value, use the File object’s read() method.

If you think of the contents of a file as a single large string value, the read() method returns the string that is
stored in the file.

Alternatively, you can use the readlines() method to get a list of string values from the file, one string for each
line of text. For example, create a file named sonnet29.txt in the same directory as hello.txt and write the
following text in it:

Tejaswini S, Assistant Professor, Dept. of AD, CIT, Gubbi


19
Module 3 Python
Make sure to separate the four lines with line breaks. Then enter the following into the interactive shell:

Note: 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.

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. You can’t write to a file you’ve opened in read mode, though. Instead, you need to open it in “write
plaintext” mode or “append plaintext” mode, or write mode and append mode for short.

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.
Append mode, on the other hand, will append text to the end of the existing file. 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.

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

First, we open bacon.txt in write mode. Since there isn’t a bacon.txt yet, Python creates one. Calling write()
on the opened file and passing write() the string argument 'Hello world! /n' writes the string to the file and
returns the number of characters written, including the newline. Then we close the file.

To add text to the existing contents of the file instead of replacing the string we just wrote, we open the file
in append mode. We write 'Bacon is not a vegetable.' to the file and close it. Finally, to print the file contents
Tejaswini S, Assistant Professor, Dept. of AD, CIT, Gubbi
20
Module 3 Python
to the screen, we open the file in its default read mode, call read(), store the resulting File object in content,
close the file, and print content.

Note: The write() method does not automatically add a newline character to the end of the string like the print()
function does.

Saving Variables with the shelve Module


You can save variables in your Python programs to binary shelf files using the shelve module. This way, your
program can restore data to variables from the hard drive. The shelve module will let you add Save and Open
features to your program.

To read and write data using the shelve module, you first import shelve. Call shelve.open() and pass it a
filename, and then store the returned shelf value in a variable. You can make changes to the shelf value as if it
were a dictionary. When you’re done, call close() on the shelf value. Here, our shelf value is stored in shelfFile.
We create a list cats and write shelfFile['cats'] = cats to store the list in shelfFile as a value associated with the
key 'cats' (like in a dictionary). Then we call close() on shelfFile.

After running the previous code on Windows, you will see three new files in the current working directory:
mydata.bak, mydata.dat, and mydata.dir. On OS X, only a single mydata.db file will be created.

These binary files contain the data you stored in your shelf. The format of these binary files is not important;
you only need to know what the shelve module does, not how it does it. The module frees you from worrying
about how to store your program’s data to a file.

Shelf values don’t have to be opened in read or write mode—they can do both once opened. Enter the following
into the interactive shell:

Here, we open the shelf files to check that our data was stored correctly. Entering shelfFile['cats'] returns the
same list that we stored earlier, so we know that the list is correctly stored, and we call close().

Just like dictionaries, shelf values have keys() and values() methods that will return list-like values of the keys
and values in the shelf. Since these methods return list-like values instead of true lists, you should pass them
to the list() function to get them in list form.

Tejaswini S, Assistant Professor, Dept. of AD, CIT, Gubbi


21
Module 3 Python

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

Saving Variables with the pprint.pformat() Function


The pprint.pprint() function will “pretty print” the contents of a list or dictionary to the screen, while the
pprint.pformat() function will return this same text as a string instead of printing it. 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. This file will be your very own
module that you can import wheneveryou want to use the variable stored in it.

Here, we import pprint to let us use pprint.pformat(). We have a list of dictionaries, stored in a variable cat.
To keep the list in cats available even after we close the shell, we 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, which we’ll call myCats.py.

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

Since Python scripts are themselves just text files with the .py file extension, your Python programs can even
generate other Python programs.

Tejaswini S, Assistant Professor, Dept. of AD, CIT, Gubbi


22
Module 3 Python

The benefit of creating a .py file (as opposed to saving variables with the shelve module) is that because it is
a text file, the contents of the file can be read and modified by anyone with a simple text editor. For most
applications, however, saving data using the shelve module is the preferred way to save variables to a file.

Only basic data types such as integers, floats, strings, lists, and dictionaries can be written to a file as simple
text. File objects, for example, cannot be encoded as text.

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. Alas, your class has a few bad eggs in it, and you can’t trust the students not to cheat. You’d like to
randomize the order of questions so that each quiz is unique, making it impossible for anyone to crib answers
from anyone else.

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.

Step 1: Store the Quiz Data in a Dictionary

The first step is to create a skeleton script and fill it with your quiz data. Create a file named
randomQuizGenerator.py, and make it look like the following:

Tejaswini S, Assistant Professor, Dept. of AD, CIT, Gubbi


23
Module 3 Python

Since this program will be randomly ordering the questions and answers, you’ll need to import the random
module u to make use of its functions. The capitals variable v contains a dictionary with US states as keys and
their capitals as values. And since you want to create 35 quizzes, the code that actually generates the quiz and
answer key files (marked with TODO comments for now) will go inside a for loop that loops 35 times w. (This
number can be changed to generate any number of quiz files.)

Step 2: Create the Quiz File and Shuffle the Question Order
Here we have to start filling in those TODOs.
The code in the loop will be repeated 35 times—once for each quiz— so you have to worry about only one
quiz at a time within the loop. First, create the actual quiz file. It needs to have a unique filename and

Tejaswini S, Assistant Professor, Dept. of AD, CIT, Gubbi


24
Module 3 Python

should also have some kind of standard header in it, with places for the student to fill in a name, date, and class
period. Then you’ll need to get a list of states in randomized order, which can be used later to create the
questions and answers for the quiz.

Add the following lines of code to randomQuizGenerator.py:

The filenames for the quizzes will be capitalsquiz<N>.txt, where <N> is a unique number for the quiz that
comes from quizNum, the for loop’s counter. The answer key for capitalsquiz<N>.txt will be stored in a text
file named capitalsquiz_answers<N>.txt. Each time through the loop, the %s placeholder in
'capitalsquiz%s.txt' and 'capitalsquiz_answers%s.txt' will be replaced by (quizNum + 1), so the first quiz and
answer key created will be capitalsquiz1.txt and capitalsquiz_answers1.txt. These files will be created with
calls to the open() function at (1) and (2), with 'w' as the second argument to open them in write mode.

The write() statements at (3) create a quiz header for the student to fill out. Finally, a randomized list of US
states is created with the help of the random.shuffle() function (4), which randomly reorders the values in any
list that is passed to it.

Step 3: Create the Answer Options


Now we 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.

Tejaswini S, Assistant Professor, Dept. of AD, CIT, Gubbi


25
Module 3 Python

The correct answer is easy to get—it’s stored as a value in the capitals dictionary (1). This loop will loop
through the states in the shuffled states list, from states[0] to states[49], find each state in capitals, and store
that state’s corresponding capital in correctAnswer.

The list of possible wrong answers is trickier. You can get it by duplicating all the values in the capitals
dictionary (2), deleting the correct answer (3), and selecting three random values from this list (4). The
random.sample() function makes it easy to do this selection. Its first argument is the list you want to select
from; the second argument is the number of values you want to select. The full list of answer options is the
combination of these three wrong answers with the correct answers (5). Finally, the answers need to be
randomized (6) so that the correct response isn’t always choice D.

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


Now write the question to the quiz file and the answer to the answer key file.

Tejaswini S, Assistant Professor, Dept. of AD, CIT, Gubbi


26
Module 3 Python

A for loop that goes through integers 0 to 3 will write the answer options in the answerOptions list (1). The
expression 'ABCD'[i] at (2) treats the string 'ABCD' as an array and will evaluate to 'A','B', 'C', and then 'D' on
each respective iteration through the loop.

In the final line (3), the expression answerOptions.index(correctAnswer) will find the integer index of the
correct answer in the randomly ordered answer options, and 'ABCD'[answerOptions.index(correctAnswer)]
will evaluate to the correct answer’s letter to be written to the answer key file.

capitalsquiz1.txt file looks like below

Tejaswini S, Assistant Professor, Dept. of AD, CIT, Gubbi


27
Module 3 Python

The corresponding capitalsquiz_answers1.txt text file

Project: Multiclipboard

Suppose you have the 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.

You can write a Python program to keep track of multiple pieces of text. This “multiclipboard” will be named
mcb.pyw (since “mcb” is shorter to type than “multiclipboard”). The .pyw extension means that Python won’t
show a Terminal window when it runs this program.

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.

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.

If you use Windows, you can easily run this script from the Run… window by creating a batch file named
mcb.bat with the following content:

Tejaswini S, Assistant Professor, Dept. of AD, CIT, Gubbi


28
Module 3 Python

Step 1: Comments and Shelf Setup


Make a skeleton script with some comments and basic setup.

It’s common practice to put general usage information in comments at the top of the file(1). If you ever forget
how to run your script, you can always look at these comments for a reminder. Then you import your modules
(2). 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 (3).

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.

If the first command line argument (which will always be at index 1 of the sys.argv list) is 'save' (1), the second
command line argument is the keyword for the current content of the clipboard. The keyword will be used as
the key for mcbShelf, and the value will be the text currently on the clipboard (2).

If there is only one command line argument, you will assume it is either 'list' or a keyword to load content onto
the clipboard. You will implement that code later. For now, just put a TODO comment there (3).

Tejaswini S, Assistant Professor, Dept. of AD, CIT, Gubbi


29
Module 3 Python

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

Finally, let’s implement the two remaining cases: The user wants to load clipboard text in from a keyword, or
they want a list of all available keywords.

If there is only one command line argument, first let’s check whether it’s 'list' (1). If so, a string representation
of the list of shelf keys will be copied to the clipboard (2). The user can paste this list into an open text editor
to read it.

Otherwise, you can assume the command line argument is a keyword. If this keyword exists in the mcbShelf
shelf as a key, you can load the value onto the clipboard (3).

Tejaswini S, Assistant Professor, Dept. of AD, CIT, Gubbi


30

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy