0% found this document useful (0 votes)
11 views31 pages

Python 1st Year BPLCK205B Module 3

Module 3 covers manipulating strings and reading/writing files in Python. It includes string methods, file paths, and the file reading/writing process, along with projects like a Password Locker and generating random quiz files. Key concepts include string manipulation techniques, file handling functions, and using modules like os and shelve.

Uploaded by

madivalshridhar1
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)
11 views31 pages

Python 1st Year BPLCK205B Module 3

Module 3 covers manipulating strings and reading/writing files in Python. It includes string methods, file paths, and the file reading/writing process, along with projects like a Password Locker and generating random quiz files. Key concepts include string manipulation techniques, file handling functions, and using modules like os and shelve.

Uploaded by

madivalshridhar1
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

Module 3

Module 3

06 08
Manipulating Reading and
Strings Writing Files

Working with Strings, Files and File Paths,


Useful String Methods, The os. path Module,
Project: Password The File
Locker, Project: Reading/Writing
Adding Bullets to Wiki Process, Saving
Mark-up Variables with the
shelve Module,…
Manipulating
Strings
Working with Strings,
Useful String Methods, Project: Password Locker, Project: Adding Bullets to Wiki Mark-up

06
Working with Strings
String Literals
• Typing string values in Python code is fairly straightforward: They begin and end with a
single quote.
• But then how can you use a quote inside a string? Typing 'That is Alice's cat.
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.
Escape Characters
• An escape character lets you use characters that are otherwise impossible to put into a
string.
• An escape character consists of a backslash (\) followed by the character you want to add
to the string.
Working with Strings cont..
Escape Characters

Escape character Prints as


\' Single quote
\" Double quote
\t Tab
\n Newline (line break)
\\ Backslash
Working with Strings cont..
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.
print(r'That is Carol\'s cat.')
Multiline Strings with Triple Quotes
• 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.
Working with Strings cont..
Multiline Comments
• a multiline string is often used for comments that span multiple lines.
Program on page number 126
Indexing and Slicing Strings
• Strings use indexes and slices the same way lists do.
The in and not in Operators with Strings
• The in and not in operators can be used with strings just like with list values.
Useful String Methods
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.
• Note that these methods do not change the string itself but return new string values.
• 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.
Examples on page number 129
Uaseful String Methods cont…
The isX String Methods
• Along with islower() and isupper(), there are several string methods that have names
beginning with the word is.
• 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.
Examples on page number 130
Useful String Methods cont…
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.
Example on page number 131
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 split() method does the opposite: It’s called on a string value and returns a list of
strings.
• You can pass a delimiter string to the split() method to specify a different string to split
upon.
Examples on page number 132
Useful String Methods cont…
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.
• 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.

Examples and program on page number 133 and 134


Useful String Methods cont…
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.
Examples on page number 135
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.
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.
• Then you can copy any account password to the clipboard and paste it into the website’s
Password field.
End of
Chapter 6

06
08
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 pprint.pformat() Function, Project: Generating Random Quiz Files, Project: Multiclipboard
Files and File Paths
• A file has two key properties: a filename (usually written as one word) and a path.
• 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.
• Fortunately, this is simple to do with the os.path.join() function.
>>> import os
>>> os.path.join('usr', 'bin', 'spam’)
'usr\\bin\\spam'
Backslash on Windows and Forward Slash on OS X and
Linux cont…..
• If this function was called 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.
• These strings will be passed to several of the file-related functions
>>> myFiles = ['accounts.txt', 'details.csv', 'invite.docx’]
>>> for filename in myFiles:
print(os.path.join('C:\\Users\\asweigart', filename))
C:\Users\asweigart\accounts.txt
C:\Users\asweigart\details.csv
C:\Users\asweigart\invite.docx
The Current Working Directory
• Every program that runs on your computer has a 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().
>>> import os
>>> os.getcwd()
‘C:\\Python34’
>>> os.chdir('C:\\Windows\\System32’)
>>> os.getcwd()
‘C:\\Windows\\System32’
• Python will display an error if you try to change to a directory that does not exist.
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: on page number 176
Creating New Folders with os.makedirs()
• Your programs can create new folders (directories) with the os.makedirs() function.
>>> import os
>>> os.makedirs('C:\\delicious\\walnut\\waffles’)
• 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.
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.
• 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.
Code Snippets on page number 177 to 178
Handling Absolute and Relative Paths cont…
• 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
>>> calcFilePath = 'C:\\Windows\\System32\\calc.exe’
>>> os.path.split(calcFilePath)
('C:\\Windows\\System32', 'calc.exe’)
• 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.
>>> calcFilePath.split(os.path.sep)
['C:', 'Windows', 'System32', 'calc.exe’]
• The os.path.sep variable is set to the correct folder-separating slash for the computer
running the program.
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.)
Code Snippets on page number 179
Checking Path Validity
• 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.
Code Snippets on page number 180
The File Reading/Writing Process
• 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.
• 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.
• The call to open() returns a File object. A File object represents a file on your computer;
Reading the Contents of Files
• If you want 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.
Code Snippets on page number 182

Writing to Files
• 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.
Writing to Files
• 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.
• 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.
Code Snippets on page number 183
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.
Code snippet on page number 184
• Your programs can use the shelve module to later reopen and retrieve the data from
these shelf files. Shelf values don’t have to be opened in read or write mode—they can
do both once opened.
Code snippet on page number 184
Saving Variables with the pprint.pformat() Function
• The pprint.pformat() function will return text as a string instead of printing it.
• 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 whenever you want to use
the variable stored in it.
Code snippet on page number 185
• 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.
Code snippet on page number 186
Projects
Project: Generating Random Quiz Files
Steps on page number 186
End of Chapter 08
End of Module 3

You might also like