0% found this document useful (0 votes)
22 views25 pages

What Is The Meaning of Single Quote and Double Quotes in String

The document explains various string methods and operations in Python like single quotes vs double quotes, escape characters, raw strings, multiline strings, indexing and slicing strings, string interpolation, f-strings, the upper(), lower(), isupper(), islower() methods, the isX() methods, startswith() and endswith() methods, the join() and split() methods, and provides examples for each.

Uploaded by

ppl.gecbidar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views25 pages

What Is The Meaning of Single Quote and Double Quotes in String

The document explains various string methods and operations in Python like single quotes vs double quotes, escape characters, raw strings, multiline strings, indexing and slicing strings, string interpolation, f-strings, the upper(), lower(), isupper(), islower() methods, the isX() methods, startswith() and endswith() methods, the join() and split() methods, and provides examples for each.

Uploaded by

ppl.gecbidar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 25

What is the meaning of single quote and double quotes in string.

Typing 'That is Alice's cat.' won’t work, because Python thinks the string ends after Alice, and the rest (s
cat.') is invalid Python code.
The string begins with a double quote, Python knows that the single quote is part of the string and not
marking the end of the string. However, if you need to use both single quotes and double quotes in the
string, you’ll need to use escape characters.
What are escape chracters expain
Escape Characters : An escape character lets you use characters that are otherwise impossible to put
into a string. An escape character consists of a backslash (\) followed by the character you want to add
to the string.
>>> spam = 'Say hi to Bob\'s mother.'
The single quote in Bob\'s has a backslash, it is not a single quote meant to end the string value. The
escape characters \' and \" let you put single quotes and double quotes inside your strings, respectively.

Write note on Raw string


Raw Strings : A raw string completely ignores all escape characters and prints any backslash that appears
in the string.
>>> print(r'That is Carol\'s cat.') //place an r before the beginning quotation mark of a string to make it a
raw string

That is Carol\'s cat.

Python considers the backslash as part of the string and not as the start of an escape character.
Raw strings are helpful while typing string values that contain many backslashes, such as the strings
used for Windows file paths like r'C:\Users\Al\Desktop' or regular expressions.

What are Multiline Strings with Triple Quotes

Instead of \n we use multiline strings concept.


A multiline string in Python begins and ends with either three single quotes or three double quotes.
Example:

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

Escaping single and double quotes is optional in multiline strings.


A multiline string is often used for comments that span multiple lines.
"""This is a test Python program. Written by Al Sweigart [email protected] This program was
designed for Python 3, not Python 2. """

Explain indexing and slicing with example


An index, gives the character at that position in the string.
A range from one index to another, the starting index is included and the ending index is not.
The space and exclamation point are included in the character count.
Example:

H e l l o , w o r l d !
'0 1 2 3 4 5 6 7 8 9 10 11 12
>>> spam = 'Hello, world!'
>>> spam[0]
'H'
>>> spam[4]
'o'
>>> spam[-1]
'!'
>>> spam[0:5]
'Hello'
>>> spam[:5]
'Hello'
>>> spam[7:]
'world!'

slicing a string capture a slice from one variable in a separate variable.


Example:
>>> spam = 'Hello, world!'
>>> fizz = spam[0:5] slicing and storing the resulting substring in another variable called fizz,
>>> fizz
'Hello'
We can have both the whole string i.e Hello world in spam and substring in fizz for quick, easy access.

Explain The in and not in Operators with Strings


An expression with two strings joined using in or not in will evaluate to a Boolean True or False.
Example:
>>> 'Hello' in 'Hello, World' // The ‘in’ operator checks string ‘Hello world’ for the substring
‘Hello’
True // output is true cus substring ‘Hello’ is present in ‘Hello world’.
>>> 'HELLO' in 'Hello, World' // The ‘in’ operator checks string ‘HELLO world’ for the substring ‘Hello’
False // HELLO and Hello both are different
>>> ' ' in 'spam' // The ‘in’ operator checks white space ‘ ‘ in string ‘spam’
True
>>> 'cats' not in 'cats and dogs'// The ‘ not in’ operator checks ‘cats’ not present in string ‘cats and
Dogs’
False // out put is false as ‘cats’ is present in ‘cats and Dogs’.

How do we put one string in another string?OR explain string interpolation.


String interpolation, in which the %s operator inside the string acts as a marker to be replaced by values
following the string.
One benefit of string interpolation is that str() doesn’t have to be called to convert values to strings.

>>> name = 'Al'


>>> age = 4000
>>> 'My name is %s. I am %s years old.' % (name, age) //instead of str() called %s is used.

'My name is Al. I am 4000 years old.' //%S is replaced by AI and 4000 respectively.

Explain f- string use


f-strings, which is similar to string interpolation except that braces are used instead of %s, with the
expressions placed directly inside the braces.
Example:
>>> namex = 'Al'
>>> age = 4000
>>> f'My name is {name}. Next year I will be {age + 1}.'

'My name is Al. Next year I will be 4001.'

Skipping the f prefix; produces the braces and their contents as part of the string value:
>>> 'My name is {name}. Next year I will be {age + 1}.'
'My name is {name}. Next year I will be {age + 1}.'//{name} ,{age+1} put in output for skipping f prefix

List Useful String Methods :


1.The upper(), lower(), isupper(), and islower() Methods
2.The isX() Methods
3.The startswith() and endswith() Methods
4. The join() and split() Methods
5. Splitting Strings with the partition() Method
6. Justifying Text with the rjust(), ljust(), and center() Methods
7. Removing Whitespace with the strip(), rstrip(), and lstrip() Methods
8. Numeric Values of Characters with the ord() and chr() Functions
9.
Explain upper(),lower() is upper() and islower() string methods with example .

The upper() : This method return a new string where all the letters in the original string have been
converted to uppercase
>>> spam = 'Hello, world!'
>>> spam = spam.upper()
>>> spam 'HELLO, WORLD!' // Nonletter characters in the string remain unchanged i.e , and !
lower() : This method return a new string where all the letters in the original string have been converted
to lowercase
>>> spam = spam.lower()
>>> spam 'hello, world!' // Nonletter characters in the string remain unchanged i.e , and !
The upper() and lower() methods are helpful if you need to make a caseinsensitive comparison.
i.e the strings 'great' and 'GREat' are not equal to each other.
The upper() and lower() methods are helpful if you need to make a caseinsensitive comparison.
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
Explain how upper() and lower() useful in making case insensitive comparison.

For example, the strings 'great' and 'GREat' are not equal to each other.
It does not matter whether the user types Great, GREAT, or grEAT, because the string is first converted
to lowercase.
print('How are you?')
feeling = input()
if feeling.lower() == 'great':
print('I feel great too.')
else:
print('I hope the rest of your day is good.')
entering a variation on great, such as GREat, will still give the output I feel great too.

Explain The isX() Methods


These methods return a Boolean value that describes the nature of the string.
The isX() string methods are helpful when you need to validate user input.
isalpha() Returns True if the string consists only of letters and isn’t blank
>>> 'hello'.isalpha()
True
>>> 'hello123'.isalpha()
False
isalnum() Returns True if the string consists only of letters and numbers and is not blank
>>> 'hello123'.isalnum()
True
>>> 'hello'.isalnum()
True
isdecimal() Returns True if the string consists only of numeric characters and is not blank
'123'.isdecimal()
True
isspace() Returns True if the string consists only of spaces, tabs, and newlines and is not blank
>>> ' '.isspace()
True
istitle() Returns True if the string consists only of words that begin with an uppercase letter followed by
only lowercase letters

>>> 'This Is Title Case'.istitle()


True
>>> 'This Is Title Case 123'.istitle()
True
>>> 'This Is not Title Case'.istitle()
False
>>> 'This Is NOT Title Case Either'.istitle()
False

Explain with example how the isX() string methods are helpful when you need to validate user input.
The following program repeatedly asks users for their age and a password until they provide valid input.
while True:
print('Enter your age:') //ask the user for their age

age = input() // store their input in age


if age.isdecimal(): // If age is a valid (decimal) value i.e true
break //break out of this first while loop
print('Please enter a number for your age.') //inform the user that they need to enter a number and
again
ask them to enter their age.
while True:
print('Select a new password (letters and numbers only):') //asks for a password
password = input() //store the user’s input in password variable
if password.isalnum(): // if the input was alphanumeric i.e true
break // break out of the loop
print('Passwords can only have letters and numbers.') // password needs to be alphanumeric and again
ask them to enter a password.
Explain The startswith() and endswith() Methods.
These methods are useful alternatives to the == equals operator.
The startswith():This method return True if the string value they are called on begins with the string
passed to the method; otherwise, they return False.
>>> 'Hello, world!'.startswith('Hello')
True
>>> 'abc123'.startswith('abcdef')
False
>>> 'Hello, world!'.startswith('Hello, world!')
True

endswith():This method return True if the string value they are called on ends with the string passed to
the method; otherwise, they return False.
>>> 'Hello, world!'.endswith('world!')
True
>>> 'Hello, world!'.endswith('Hello, world!')
True

>>> 'abc123'.endswith('12')
False
Explain The join() and split() Methods
The join() method is called on a string, gets passed a list of strings, and returns a string.
join() is called on a string value and is passed a list value
>>> ', '.join(['cats', 'rats', 'bats']) // join(['cats', 'rats', 'bats']) is called on the ', ' string, the returned string
is 'cats, rats, bats'.
'cats, rats, bats'
>>> ' '.join(['My', 'name', 'is', 'Simon'])
'My name is Simon'
>>> 'ABC'.join(['My', 'name', 'is', 'Simon'])
'MyABCnameABCisABCSimon'

The split() method does the opposite: It’s called on a string value and returns a list of strings.
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 newlines and
return a list in which each item corresponds to one line of the string.
>>> 'My name is Simon'.split()
['My', 'name', 'is', 'Simon']
the string 'My name is Simon' is split wherever whitespace characters such as the space, tab, or newline
characters are found.

Explain the partition() Method


The partition() string method can split a string into the text before and after a separator string.
Example:
>>> 'Hello, world!'.partition('w')
('Hello, ', 'w', 'orld!')
 searches the string ‘w’ it is called on for the separator string it is passed, and returns a tuple of
three substrings for the “before,” i.e ‘Hello’ “separator,” i.e ‘w’ and “after” substrings i.e ‘orld!
>>> 'Hello, world!'.partition('world')
('Hello, ', 'world', '!')
 searches the string ‘world’ it is called on for the separator string it is passed, and returns a tuple
of three substrings for the “before,” i.e ‘Hello’ “separator,” i.e ‘world’ and “after” substrings i.e
‘!’
’.
 If the separator string you pass to partition() occurs multiple times in the string that partition()
calls on, the method splits the string only on the first occurrence:
>>> 'Hello, world!'.partition('o')
('Hell', 'o', ', world!')
O occurred in hello and in world but ‘hell’ ‘o’ ‘world’ is considered but not second
occurance of ‘o’.

 the separator string can’t be found, the first string returned in the tuple will be the entire string,
and the other two strings will be empty:
>>> 'Hello, world!'.partition('XYZ')
('Hello, world!', '', '')
i.e XYZ is not present in the string hence Before string is returned that is ‘Hello ,World!’ separator string
and after strings are empty.
 the multiple assignment trick to assign the three returned strings to three variables
>>> before, sep, after = 'Hello, world!'.partition(' ')
>>> before 'Hello,'
>>> after 'world!'

Explain string justifying methods


The rjust():
the string they are called on, with spaces inserted to justify the text at right.
>>> 'Hello'.rjust(10)
' Hello' //10 whitespaces are added to right side
ljust() : the string they are called on, with spaces inserted to justify the text at left.
>>> 'Hello'.ljust(10)
'Hello ‘ //10 whitespaces are added to left side

The center() : centers the text rather than justifying it to the left or right.
>>> 'Hello'.center(20)
' Hello '
An optional second argument to rjust() and ljust() will specify a fill character other than a space
character.
>>> 'Hello'.rjust(20, '*') //instead of whitspace ***** is padded
'***************Hello'
>>> 'Hello'.ljust(20, '-')
'Hello---------------' //instead of whitspace ------------ is padded

>>> 'Hello'.center(20, '=')


'=======Hello========'//instead of whitspace ====== is padded

These methods are especially useful when you need to print tabular data that has correct spacing.
Using rjust(), ljust(), and center() lets you ensure that strings are neatly aligned.

Explain the strip(), rstrip(), and lstrip() Methods

The strip() string method will return a new string without any whitespace characters at the beginning or
end.
>>> spam = ' Hello, World '
>>> spam.strip() // strip method called on ‘ Hello, World! ‘
'Hello, World' // stripped whitespaces on bothe sides

The lstrip() : method will remove whitespace characters from the left ends

>>> spam.lstrip()
'Hello, World '
rstrip(): method will remove whitespace characters from the left right ends,

>>> spam.rstrip()
' Hello, World'

a string argument will specify which characters on the ends should be stripped.
>>> spam = 'SpamSpamBaconSpamEggsSpamSpam'
>>> spam.strip('ampS')
'BaconSpamEggs'
//Passing strip() the argument 'ampS' will tell it to strip occurrences of a, m, p, and capital S from both
the ends of the string stored in spam.
The order of the characters in the string passed to strip() does not matter:
strip('ampS') , strip('mapS') or strip('Spam') all are same strip off a,m,p and S occurances before and
after.

Why we need files :


1.This is because the variables used in a program have a lifetime that lasts till the time
the program is under execution.
2.if we want to store the data that were input as well as the generated output
permanently so that we can reuse it later.
3. Usually, organisations would want to permanently store information about employees,
inventory, sales, etc.
4.to avoid repetitive tasks of entering the same data.
5.Hence, data are stored permanently on secondary storage devices for reusability
Files :
Definition: A file is a named location on a secondary storage media where data are
permanently stored for later access.
Or
File is a named location on disk to store related information, as the file is having some
name and location, it is stored in hard disk.
Types of file
Generally we divide files in two categories,
1.text file : A text file consists of human readable characters, which can be opened by
any text editor. On the other hand.
Example: • Document files: .pdf, .doc, .xls etc. • Image files: .png, .jpg, .gif, .bmp etc. •
Video files: .mp4, .3gp, .mkv, .avi etc. • Audio files: .mp3, .wav, .mka, .aac etc. •
Database files: .mdb, .accde, .frm, .sqlite etc. • Archive files: .zip, .rar, .iso, .7z etc. •
Executable files: .exe, .dll, .class etc.
Example: • Web standards: html, XML, CSS, JSON etc. • Source code: c, app, js, py,
java etc. • Documents: txt, tex, RTF etc. • Tabular data: csv, tsv etc. • Configuration: ini,
cfg, reg etc.
2.binary file: binary files are made up of non-human readable characters and symbols,
which require specific programs to access its contents.

Define file path


The file path is a string that represents the location of a file.
It’s broken up into three major parts:

1. Folder Path: the file folder location on the file system where subsequent folders
are separated by a forward slash / (Unix) or backslash \ (Windows)
2. File Name: the actual name of the file
3. Extension: the end of the file path pre-pended with a period (.) used to indicate
the file type

Backslash on Windows and Forward Slash on macOS and Linux On Windows, paths
are written using backslashes (\) as the separator between folder names. The macOS
and Linux operating systems,
Explain path()
the Path() function in the pathlib module, If you pass it the string values of individual file
and folder names in your path, Path() will return a string with a file path using the correct
path separators.
>>> from pathlib import Path
>>> Path('spam', 'bacon', 'eggs')
WindowsPath('spam/bacon/eggs')
If you want to get a simple text string of this path, you can pass it to the str() function,
which in our example returns 'spam\\bacon\\eggs'.

>>> str(Path('spam', 'bacon', 'eggs'))


'spam\\bacon\\eggs'
(Notice that the backslashes are doubled because each backslash needs to be escaped
by another backslash character.)

Why always use forward slashes in your Python code?


Path(r'spam\eggs') refers to two separate folders (or a file eggs in a folder spam) on
Windows, the same command would refer to a single folder (or file) named spam\eggs
on macOS and Linux. For this reason, it’s usually a good idea to always use forward
slashes in your Python code.
Explain / operator to join paths

the / operator combine Path objects and strings. This is helpful for modifying a Path
object after you’ve already created it with the Path() function.
>>> from pathlib import Path
>>> Path('spam')
/ 'bacon' / 'eggs'
WindowsPath('spam/bacon/eggs')
>>> Path('spam') / Path('bacon/eggs')
WindowsPath('spam/bacon/eggs')
>>> Path('spam') / Path('bacon', 'eggs')
WindowsPath('spam/bacon/eggs')

What is file object:


A file object allows us to use, access and manipulate all the user accessible files. One
can read and write any such files. Using file objects, we can read or write any files.
What is current working directory
The folder where the Python script is running is known as the Current Directory. This
may not be the path where the Python script is located.

To return the directory you are currently in, we use the OS module to interact with the
operating system. Under the OS module, we use the os.getcwd()) method to return the
path of the current directory.

You can get the current working directory as a string value with the Path.cwd() function
>>> from pathlib import Path >>> import os >>> Path.cwd()
WindowsPath('C:/Users/Al/AppData/Local/Programs/Python/Python37')'
change it using os.chdir()
>>> os.chdir('C:\\Windows\\System32')
>>> Path.cwd()
WindowsPath('C:/Windows/System32')
.
The Home Directory
A home directory is a file system directory on a multi-user operating system
containing files for a given user of the system.
(1) A storage folder that contains the user's personal files. Starting with Windows
Vista, the Windows home directory is \user\username.
(2) You can get a Path object of the home folder by calling Path.home():
(3) >>> Path.home()
(4) WindowsPath('C:/Users/Al')

Absolute vs. Relative Paths


There are two ways to specify a file path:
• An absolute path, which always begins with the root folder
n absolute file path describes how to access a given file or directory, starting from the
root of the file system
• A relative path, which is relative to the program’s current working directory There are
also the dot (.) and dot-dot (..) folders. A relative file path is interpreted from the
perspective your current working directory. If you use a relative file path from the wrong
directory, then the path will refer to a different file than you intend, or it will refer to no
file at all.
These are not real folders but special names that can be used in a path.

Relative Paths
A relative path is the path that (as the name sounds) is relative to the working directory
location on your computer.
If the working directory is earth-analytics, then Python knows to start looking for your
files in the earth-analytics directory.
Following the example above, if you set the working directory to the earth-
analytics directory, then the relative path to access streams.csv would be:
data/field-sites/california/colorado/streams.csv
Data Tip The default working directory in any Jupyter Notebook file is the directory in
which it is saved. However, you can change the working directory in your code!
However, imagine that you set your working directory to earth-analytics/data which is a
subdirectory of earth-analytics.
The correct relative path to the streams.csv file would now look like this:
field-sites/california/colorado/streams.csv
Relative paths are useful if you can count on whoever is running your code to have a
working directory setup similar to yours. When the details of your directory setup are
shared with others who can replicate it, then you can use relative paths to support
reproducibility and collaboration.

Absolute Paths
An absolute path is a path that contains the entire path to the file or directory that you
need to access. This path will begin at the home directory of your computer and will end
with the file or directory that you wish to access.
/home/your-username/earth-analytics/data/field-sites/california/colorado/streams.csv
Absolute paths ensure that Python can find the exact file on your computer.
However, as you have seen, computers can have a different path constructions,
depending on the operating system, and contain usernames that unique to that specific
machine.
There are ways to overcome this issue and others associated with finding files on
different machines using tools such as the os package in Python.
Handling Absolute and Relative Paths
Calling the is_absolute() method on a Path object will return True if it represents an
absolute path or False if it represents a relative path.
>>> Path.cwd()
WindowsPath('C:/Users/Al/AppData/Local/Programs/Python/Python37')
>>> Path.cwd().is_absolute()
True
>>> Path('spam/bacon/eggs').is_absolute()
False
To get an absolute path from a relative path, you can put Path.cwd() / in front of the
relative Path object.
>>> Path('my/relative/path')
WindowsPath('my/relative/path')
>>> Path.cwd() / Path('my/relative/path')
WindowsPath('C:/Users/Al/AppData/Local/Programs/Python/Python37/my/relative/
path')
If your relative path is relative to another path besides the current working directory,
just replace Path.cwd() with that other path instead.
The following example gets an absolute path using the home directory instead of the
current working directory:
>>> Path('my/relative/path')
WindowsPath('my/relative/path')
>>> Path.home() / Path('my/relative/path')
WindowsPath('C:/Users/Al/my/relative/path')
Explain os.path module
The OS module is a function that allows interaction with the operating system. It is a
part of the standard utility modules of Python. This feature contains the functions to
fetch the information that is based on the local directories, processes, files, and
environmental variables.
The main functionality of this module includes merging, normalizing, and fetching the
path names in python. As this feature is useful in applying the function on paths, the
parameters of paths are passed either in the form of strings or bytes.
The os.path module also has some useful functions related to absolute and
relative paths:
• Calling os.path.abspath(path) will return a string of the absolute path of the argument.
This is an easy way to convert a relative path into an absolute one.
• Calling os.path.isabs(path) will return True if the argument is an absolute path and
False if it is a relative path.
• Calling os.path.relpath(path, start) will return a string of a relative path from the start
path to path. If start is not provided, the current working directory is used as the start
path.
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 directory (or dir) name and base name of a path
are outlined . C:\Windows\System32\calc.exe Dir name Base name .
The base name follows the last slash in a path and is the same as the filename. The dir
name is everything before the last slash
,
os.path.split() to get a tuple value with these two strings, 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.
The split() string method will work to return a list of each part of the path.

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.

>>> os.path.getsize('C:\\Windows\\System32\\calc.exe')

27648

the calc.exe program on my computer is 27,648 bytes in size,

• Calling os.listdir(path) will return a list of filename strings for each file in the path argument.

>>> os.listdir('C:\\Windows\\System32')

['0409', '12520437.cpx', '12520850.cpx', '5U877.ax', 'aaclient.dll', --snip-- 'xwtpdui.dll',


'xwtpw32.dll', 'zh-CN', 'zh-HK', 'zh-TW', 'zipfldr.dll']

(Note that this function is in the os module, not os.path.)

to find the total size of all the files in this director, use os.path.getsize() and os.listdir() together.

>>> totalSize = 0

>>> for filename in os.listdir('C:\\Windows\\System32'):

//loop over each filename in the C:\Windows\System32 folder, the totalSize variable is
incremented by the size of each file.

totalSize = totalSize + os.path.getsize(os.path.join('C:\\Windows\\System32', filename))

//call os.path.getsize(),

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


>>> print(totalSize)

//After looping through all the files, print totalSize to see the total size of the C:\Windows\
System32 folder.

2559970473

Modifying a List of Files Using Glob Patterns

glob (short for global) is used to return all file paths that match a specific pattern.

>>> list(p.glob('*.txt') # Lists all text files.

The glob pattern '*.txt' will return files that start with any combination of characters as long as it ends
with the string '.txt', which is the text file extension.

>>> list(p.glob('project?.docx')

The glob expression 'project?.docx' will return 'project1.docx' or 'project5.docx', but it will not return
'project10.docx', because ? only matches to one character—so it will not match to the two-character
string '10'.

>>> list(p.glob('*.?x?')

The glob expression '*.?x?' will return files with any name and any three-character extension where the
middle character is an 'x'. combine the asterisk and question mark to create even more complex glob
expressions, l

the glob module is used similarly to find, locate, and search for all of the files that are
present in a system.

The glob module in Python does not require separate installations and comes with
every default Python installation.

Although glob is a module that comes with the default Python installation, it still requires
a separate import statement.

import glob

After the import, we have to refer to every function and method in this module with the
prefix glob.

Let's see how to use glob in Python.


This basic example will make use of a function inside the glob class called glob() itself.

import glob
files = glob.glob("./glob/home/sample_files/*") # Creating a glob object
print(files)

 This snippet of code prints all the files within the sample_files folder located in the
home folder of the glob directory. The asterisk (*) stands for “multiple of any characters,
Asterisk (*): Matches zero or more characters

 Question Mark (?) Matches exactly one character

Difference between regex and glob

Regex and Glob patterns are similar ways of matching patterns in strings.

The main difference is that the regex pattern matches strings in code, while globbing matches file names
or file content in the terminal.

Globbing is the shell's way of providing regular expression patterns like other programming languages.

Another big difference is that regex has more options and features than glob patterns. It's more
advanced, and globbing has fewer options to get you through your search faster.

Checking Path Validity

Path objects have methods to check whether a given path exists and whether it is a file or folder. a
variable p holds a Path object

Calling p.exists() returns True if the path exists or returns False if it doesn’t exist.

• Calling p.is_file() returns True if the path exists and is a file, or returns False otherwise.

• Calling p.is_dir() returns True if the path exists and is a directory, or returns False otherwise.

The File Reading/Writing Process

Plaintext files contain only basic text characters and do not include font, size, or color information.

Text files with the .txt extension or Python script files with the .py extension are examples of plaintext
files.
These can be opened with Windows’s Notepad or macOS’s TextEdit application.

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.

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

open files using the open() method.

The open() function in Python accepts two arguments.

The first one is the file name along with the complete path and

the second one is the file open mode.

The open() function returns a File object

create a text file named hello.txt using Notepad .

Type Hello, world! as the content of this text file and save it in your user home folder.

Then enter the following into the interactive shell:

Syntax: >>> helloFile = open(Path.home() / 'hello.txt')

>>> helloFile = open('C:\\Users\\your_home_folder\\hello.txt') (for windows)

>>> helloFile = open('/Users/your_home_folder/hello.txt') (for Mac Os)

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


Define file’s read mode?

Read mode is the default mode for files you open in Python. When a file is opened in read mode, Python
lets you only read data from the file;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/Al/hello .txt', 'r') and open('/Users/Al/hello.txt') do the same thing.

Explain How to Read 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.
Let’s continue with the hello.txt File object you stored in helloFile.

Enter the following into the interactive shell:

>>> helloContent = helloFile.read()

>>> helloContent

'Hello, world!'

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.

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:

When, in disgrace with fortune and men's eyes, I all alone beweep my outcast state, And trouble deaf
heaven with my bootless cries, And look upon myself and curse my fate, Make sure to separate the four
lines with line breaks.

Then enter the following into the interactive shell:

>>> sonnetFile = open(Path.home() / 'sonnet29.txt')

>>> sonnetFile.readlines()

[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, except for the last line of the file, each of the string values ends with a newline character \n.
A list of strings is often easier to work with than a single large string value.
Explain write() method

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.

To write into a file you’ve opened in read mode. 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.

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.

Enter the following into the interactive shell:

>>> baconFile = open('bacon.txt', 'w') // First, we open bacon.txt in write mode

>>> baconFile.write('Hello, world!\n') // Calling write() on the opened file and passing write() the string
argument 'Hello, world! /n' writes the string to the file

13 // and returns the number of characters written, including the newline.

>>> baconFile.close() // Then we close the file.

. To add text to the existing contents of the file instead of replacing the string we just wrote,

>>> baconFile = open('bacon.txt', 'a') // we open the file in append mode.

>>> baconFile.write('Bacon is not a vegetable.') // We write 'Bacon is not a vegetable.' to the file

>>> baconFile.close()// close it bacon.txt file.

>>> baconFile = open('bacon.txt') // open the file in its default read mode, , close the file,
>>> content = baconFile.read() // call read(), store the resulting File object in content

>>> baconFile.close()// close it bacon.txt file

>>> print(content) // and print content

Hello, world! Bacon is not a vegetable

the shelve Module

Shelve Module, an effective tool for storing or persistent data storage. The shelve
module will let you add Save and Open features to your program.

The Shelve module is used to store data when using a relational database is not
recommended. A shelf object is a dictionary-like object, which is defined in this
module. Keys in shelf objects are strings and values are Python objects, that can be
handled by the Pickle module. The shelve module comes with Python’s standard utility
module, so there is no need to install it externally. The shelve module is used when
we need to store data that is small in size and less complex. For large and
complex data we use a database
The Shelf object has following methods available −

Sr.No Methods & Description


.

1
close()
synchronise and close persistent dict object.

2
sync()
Write back all entries in the cache if shelf was opened with writeback set to
True.

3
get()
returns value associated with key

4
items()
list of tuples – each tuple is key value pair

5
keys()
list of shelf keys

6
pop()
remove specified key and return the corresponding value.

7
update()
Update shelf from another dict/iterable

8
values()
list of shelf values

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

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.

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

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

>>> import shelve //To read and write data using the shelve module, you first import shelve.,

>>> shelfFile = shelve.open('mydata') // Call shelve.open() and pass it a filename

>>> cats = ['Zophie', 'Pooka', 'Simon'] // When We create a list cats and then store the returned shelf
value in a variable.

>>> shelfFile['cats'] = cats // write shelfFile['cats'] = cats to store the list in shelfFile as a value associated
with the key 'cats' (like in a dictionary). and You can make changes to the shelf value as if it were a
dictionary.

>>> shelfFile.close() // you’re done, call close() on the shelf value


Here, our shelf value is stored in shelfFile. 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. >>> shelfFile = shelve.open('mydata') // we open
the shelf files to check that our data was stored correctly

>>> type(shelfFile)

>>> shelfFile['cats'] // Entering shelfFile['cats'] returns the same list that we stored earlier,

['Zophie', 'Pooka', 'Simon'] // the same list that we stored earlier,

>>> shelfFile.close() // we call close().

Explain the pprint.pformat() Function

The pprint module provides a capability to “pretty-print” arbitrary Python data


structures in a well-formatted and more readable way!

One unique feature of pprint output is that the dictionaries are automatically sorted before the
display representation is formatted.
The pprint module contains definition of PrettyPrinter class. Its constructor takes
following format −
Syntax:
pprint.PrettyPrinter(indent, width, depth, stream, compact)
The indent parameter defines indentation added on each recursive level. Default is 1.
The width parameter by default is 80. Desired output is restricted by this value. If the
length is greater than width, it is broken in multiple lines.
The depth parameter controls number of levels to be printed.
The stream parameter is by default std.out – the default output device. It can take any
stream object such as file.
The compact parameter id set to False by default. If true, only the data adjustable
within width will be displayed.
The PrettyPrinter class defines following methods −
pprint() − prints the formatted representation of PrettyPrinter object
pformat() − Returns the formatted representation of object, based on parameters to the
constructor.
# A python code without pprint
import requests

def geocode(address):
url = "https://maps.googleapis.com/maps/api/geocode/json"
resp = requests.get(url, params = {'address': address})
return resp.json()

# calling geocode function


data = geocode('India gate')

# printing json response


print(data)

The output of above program looks like this:


{'status': 'OK', 'results': [{'address_components': [{'long_name':
'Rajpath', 'types': ['route'],
'short_name': 'Rajpath'}, {'long_name': 'India Gate', 'types':
['political', 'sublocality',
'sublocality_level_1'], 'short_name': 'India Gate'}, {'long_name':
'New Delhi', 'types':
['locality', 'political'], 'short_name': 'New Delhi'}, {'long_name':
'New Delhi',
'types': ['administrative_area_level_2', 'political'], 'short_name':
'New Delhi'}, {'long_name':
'Delhi', 'types': ['administrative_area_level_1', 'political'],
'short_name': 'DL'}, {'long_name':
'India', 'types': ['country', 'political'], 'short_name': 'IN'},
{'long_name': '110001', 'types':
['postal_code'], 'short_name': '110001'}], 'geometry': {'location':
{'lng': 77.2295097, 'lat': 28.612912},
'viewport': {'northeast': {'lng': 77.2308586802915, 'lat':
28.6142609802915}, 'southwest': {'lng':
77.22816071970848, 'lat': 28.6115630197085}}, 'location_type':
'APPROXIMATE'}, 'types':
['establishment', 'point_of_interest'], 'formatted_address':
'Rajpath, India Gate, New Delhi, Delhi 110001,
India', 'place_id': 'ChIJC03rqdriDDkRXT6SJRGXFwc'}]}

# A python code with pprint


import requests
from pprint import pprint

def geocode(address):
url = "https://maps.googleapis.com/maps/api/geocode/json"
resp = requests.get(url, params = {'address': address})
return resp.json()

# calling geocode function


data = geocode('India gate')

# pretty-printing json response


pprint(data)
The output of above code looks like this:
{'results': [{'address_components': [{'long_name': 'Rajpath',
'short_name': 'Rajpath',
'types': ['route']},
{'long_name': 'India Gate',
'short_name': 'India Gate',
'types': ['political',
'sublocality',
'sublocality_level_1']},
{'long_name': 'New Delhi',
'short_name': 'New Delhi',
'types': ['locality', 'political']},
{'long_name': 'New Delhi',
'short_name': 'New Delhi',
'types':
['administrative_area_level_2',
'political']},
{'long_name': 'Delhi',
'short_name': 'DL',
'types':
['administrative_area_level_1',
'political']},
{'long_name': 'India',
'short_name': 'IN',
'types': ['country', 'political']},
{'long_name': '110001',
'short_name': '110001',
'types': ['postal_code']}],
'formatted_address': 'Rajpath, India Gate, New Delhi, Delhi '
'110001, India',
'geometry': {'location': {'lat': 28.612912, 'lng':
77.2295097},
'location_type': 'APPROXIMATE',
'viewport': {'northeast': {'lat':
28.6142609802915,
'lng':
77.2308586802915},
'southwest': {'lat':
28.6115630197085,
'lng':
77.22816071970848}}},
'place_id': 'ChIJC03rqdriDDkRXT6SJRGXFwc',
'types': ['establishment', 'point_of_interest']}],
'status': 'OK'}

Project: Generating Random Quiz Files

You might also like