Unit 4 Python
Unit 4 Python
UNIT-4
Python Data Types
Data types are the classification or categorization of data items. It represents the
kind of value that tells what operations can be performed on a particular data. Since
everything is an object in Python programming, data types are actually classes and
variables are instances (object) of these classes. The following are the standard or
built-in data types in Python:
Numeric
Sequence Type
Boolean
Set
Dictionary
Binary Types( memoryview, bytearray, bytes)
To define the values of various data types and check their data types we use
the type() function. Consider the following examples.
Python3
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
# DataType Output: str
x = "Hello World"
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
Integers – This value is represented by int class. It contains positive or negative
whole numbers (without fractions or decimals). In Python, there is no limit to
how long an integer value can be.
Float – This value is represented by the float class. It is a real number with a
floating-point representation. It is specified by a decimal point. Optionally, the
character e or E followed by a positive or negative integer may be appended to
specify scientific notation.
Complex Numbers – Complex number is represented by a complex class. It is
specified as (real part) + (imaginary part)j. For example – 2+3j
Note – type() function is used to determine the type of data type.
Python3
# Python program to
# demonstrate numeric value
a=5
print("Type of a: ", type(a))
b = 5.0
print("\nType of b: ", type(b))
c = 2 + 4j
print("\nType of c: ", type(c))
Output:
Type of a: <class 'int'>
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
Strings in Python can be created using single quotes or double quotes or even triple
quotes.
Python3
# Creating a String
# with single Quotes
String1 = 'Welcome to the Geeks World'
print("String with the use of Single Quotes: ")
print(String1)
# Creating a String
# with double Quotes
String1 = "I'm a Geek"
print("\nString with the use of Double Quotes: ")
print(String1)
print(type(String1))
# Creating a String
# with triple Quotes
String1 = '''I'm a Geek and I live in a world of "Geeks"'''
print("\nString with the use of Triple Quotes: ")
print(String1)
print(type(String1))
Output:
String with the use of Single Quotes:
Welcome to the Geeks World
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
<class 'str'>
String1 = "GeeksForGeeks"
print("Initial String: ")
print(String1)
Output:
Initial String:
GeeksForGeeks
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
Lists are just like arrays, declared in other languages which is an ordered collection
of data. It is very flexible as the items in a list do not need to be of the same type.
Creating List
Lists in Python can be created by just placing the sequence inside the square
brackets[].
Python3
# Creating a List
List = []
print("Initial blank List: ")
print(List)
Output:
Initial blank List:
[]
Multi-Dimensional List:
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
[['Geeks', 'For'], ['Geeks']]
Python Access List Items
In order to access the list items refer to the index number. Use the index operator [ ]
to access an item in a list. In Python, negative sequence indexes represent positions
from the end of the array. Instead of having to compute the offset as in
List[len(List)-3], it is enough to just write List[-3]. Negative indexing means
beginning from the end, -1 refers to the last item, -2 refers to the second-last item,
etc.
Python3
Output:
Accessing element from the list
Geeks
Geeks
Accessing element using negative indexing
Geeks
Geeks
Note – To know more about Lists, refer to Python List.
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
Just like a list, a tuple is also an ordered collection of Python objects. The only
difference between a tuple and a list is that tuples are immutable i.e. tuples cannot
be modified after it is created. It is represented by a tuple class.
Creating a Tuple
In Python, tuples are created by placing a sequence of values separated by a
‘comma’ with or without the use of parentheses for grouping the data sequence.
Tuples can contain any number of elements and of any datatype (like strings,
integers, lists, etc.). Note: Tuples can also be created with a single element, but it is
a bit tricky. Having one element in the parentheses is not sufficient, there must be a
trailing ‘comma’ to make it a tuple.
Python3
# Creating a Tuple
# with nested tuples
Tuple1 = (0, 1, 2, 3)
Tuple2 = ('python', 'geek')
Tuple3 = (Tuple1, Tuple2)
print("\nTuple with nested tuples: ")
print(Tuple3)
Output:
Initial empty Tuple:
()
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
('Geeks', 'For')
# Python program to
# demonstrate accessing tuple
Output:
First element of tuple
1
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
# Python program to
# demonstrate boolean type
print(type(True))
print(type(False))
print(type(true))
Output:
<class 'bool'>
<class 'bool'>
Traceback (most recent call last):
File "/home/7e8862763fb66153d70824099d4f5fb7.py", line 8, in
print(type(true))
NameError: name 'true' is not defined
Set Data Type in Python
In Python, a Set is an unordered collection of data types that is iterable, mutable and
has no duplicate elements. The order of elements in a set is undefined though it may
consist of various elements.
Create a Set in Python
Sets can be created by using the built-in set() function with an iterable object or a
sequence by placing the sequence inside curly braces, separated by a ‘comma’. The
type of elements in a set need not be the same, various mixed-up data type values
can also be passed to the set.
Python3
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
# Creating a Set
set1 = set()
print("Initial blank Set: ")
print(set1)
Output:
Initial blank Set:
set()
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
# Python program to demonstrate
# Accessing of elements in a set
# Creating a set
set1 = set(["Geeks", "For", "Geeks"])
print("\nInitial set")
print(set1)
Output:
Initial set:
{'Geeks', 'For'}
Elements of set:
Geeks For
True
Note – To know more about sets, refer to Python Sets.
Dictionary Data Type in Python
A dictionary in Python is an unordered collection of data values, used to store data
values like a map, unlike other Data Types that hold only a single value as an
element, a Dictionary holds a key: value pair. Key-value is provided in the
dictionary to make it more optimized. Each key-value pair in a Dictionary is
separated by a colon : , whereas each key is separated by a ‘comma’.
Create a Dictionary
In Python, a Dictionary can be created by placing a sequence of elements within
curly {} braces, separated by ‘comma’. Values in a dictionary can be of any
datatype and can be duplicated, whereas keys can’t be repeated and must be
immutable. The dictionary can also be created by the built-in function dict(). An
empty dictionary can be created by just placing it in curly braces{}. Note –
Dictionary keys are case sensitive, the same name but different cases of Key will be
treated distinctly.
Python3
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Creating a Dictionary
# with Integer Keys
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)
# Creating a Dictionary
# with Mixed keys
Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)
# Creating a Dictionary
# with dict() method
Dict = dict({1: 'Geeks', 2: 'For', 3: 'Geeks'})
print("\nDictionary with the use of dict(): ")
print(Dict)
# Creating a Dictionary
# with each item as a Pair
Dict = dict([(1, 'Geeks'), (2, 'For')])
print("\nDictionary with each item as a pair: ")
print(Dict)
Output:
Empty Dictionary:
{}
Dictionary with the use of Integer Keys:
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Dictionary with the use of Mixed Keys:
{1: [1, 2, 3, 4], 'Name': 'Geeks'}
Dictionary with the use of dict():
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Dictionary with each item as a pair:
{1: 'Geeks', 2: 'For'}
Accessing Key-value in Dictionary
In order to access the items of a dictionary refer to its key name. Key can be used
inside square brackets. There is also a method called get() that will also help in
accessing the element from a dictionary.
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
Python3
# Creating a Dictionary
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
Output:
Accessing a element using key:
For
Accessing a element using get:
Geeks
Python String
A String is a data structure in Python that represents a sequence
of characters. It is an immutable data type, meaning that once
you have created a string, you cannot change it. Strings are
used widely in many different applications, such as storing and
manipulating text data, representing names, addresses, and
other types of data that can be represented as text.
Python3
print("A Computer Science portal for
geeks")
print('A')
Output:
A Computer Science portal for geeks
A
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
Creating a String in Python
Strings in Python can be created using single quotes or double quotes or even triple
quotes. Let us see how we can define a string in Python.
Example:
Python3
# Python Program for
# Creation of String
# Creating a String
# with single Quotes
String1 = 'Welcome to the Geeks World'
print("String with the use of Single Quotes: ")
print(String1)
# Creating a String
# with double Quotes
String1 = "I'm a Geek"
print("\nString with the use of Double Quotes: ")
print(String1)
# Creating a String
# with triple Quotes
String1 = '''I'm a Geek and I live in a world of "Geeks"'''
print("\nString with the use of Triple Quotes: ")
print(String1)
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
For
Life'''
print("\nCreating a multiline String: ")
print(String1)
Output:
While accessing an index out of the range will cause an IndexError. Only
Integers are allowed to be passed as an index, float or other types that will cause
a TypeError.
Example:
In this example, we will define a string in Python and access its characters using
positive and negative indexing. The 0th element will be the first character of the
string whereas the -1th element is the last character of the string.
Python3
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
# Python Program to Access
# characters of String
String1 = "GeeksForGeeks"
print("Initial String: ")
print(String1)
Output:
Initial String:
GeeksForGeeks
First character of String is:
G
Last cha racter of String is:
s
String Slicing
In Python, the String Slicing method is used to access a range of characters in the
String. Slicing in a String is done by using a Slicing operator, i.e., a colon (:). One
thing to keep in mind while using this method is that the string returned after slicing
includes the character at the start index but not the character at the last index.
Example:
In this example, we will use the string-slicing method to extract a substring of the
original string. The [3:12] indicates that the string slicing will start from the 3rd
index of the string to the 12th index, (12th character not including). We can also use
negative indexing in string slicing.
Python3
# Python Program to
# demonstrate String slicing
# Creating a String
String1 = "GeeksForGeeks"
print("Initial String: ")
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
print(String1)
Output:
Initial String:
GeeksForGeeks
Slicing characters from 3-12:
ksForGeek
Slicing characters between 3rd and 2nd last character:
ksForGee
Example:
In this example, we will reverse a string by accessing the index. We did not specify
the first two parts of the slice indicating that we are considering the whole string,
from the start index to the last index.
Python3
Output:
skeegrofskeeg
Example:
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
We can also reverse a string by using built-in join and reversed functions, and
passing the string as the parameter to the reversed() function.
Python3
# Program to reverse a string
gfg = "geeksforgeeks"
print(gfg)
Output:
skeegrofskeeg
Deleting/Updating from a String
In Python, the Updation or deletion of characters from a String is not allowed. This
will cause an error because item assignment or item deletion from a String is not
supported. Although deletion of the entire String is possible with the use of a built-
in del keyword. This is because Strings are immutable, hence elements of a String
cannot be changed once assigned. Only new strings can be reassigned to the same
name.
Updating a character
A character of a string can be updated in Python by first converting the string into
a Python List and then updating the element in the list. As lists are mutable in
nature, we can update the character and then convert the list back into the String.
Another method is using the string slicing method. Slice the string before the
character you want to update, then add the new character and finally add the other
part of the string again by string slicing.
Example:
In this example, we are using both the list and the string slicing method to update a
character. We converted the String1 to a list, changes its value at a particular
element, and then converted it back to a string using the Python string
join() method.
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
In the string-slicing method, we sliced the string up to the character we want to
update, concatenated the new character, and finally concatenate the remaining part
of the string.
Python3
#2
String3 = String1[0:2] + 'p' + String1[3:]
print(String3)
Output:
Initial String:
Hello, I'm a Geek
Updating character at 2nd Index:
Heplo, I'm a Geek
Heplo, I'm a Geek
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
As Python strings are immutable in nature, we cannot update the existing string. We
can only assign a completely new value to the variable with the same name.
Example:
In this example, we first assign a value to ‘String1’ and then updated it by assigning
a completely different value to it. We simply changed its reference.
Python3
# Updating a String
String1 = "Welcome to the Geek World"
print("\nUpdated String: ")
print(String1)
Output:
Initial String:
Hello, I'm a Geek
Updated String:
Welcome to the Geek World
Deleting a character
Python strings are immutable, that means we cannot delete a character from it.
When we try to delete thecharacter using the del keyword, it will generate an error.
Python3
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
Output:
Initial String:
Hello, I'm a Geek
Deleting character at 2nd Index:
Traceback (most recent call last):
File "e:\GFG\Python codes\Codes\demo.py", line 9, in <module>
del String1[2]
TypeError: 'str' object doesn't support item deletion
But using slicing we can remove the character from the original string and store the
result in a new string.
Example:
In this example, we will first slice the string up to the character that we want to
delete and then concatenate the remaining string next from the deleted character.
Python3
# Deleting a character
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
# of the String
String2 = String1[0:2] + String1[3:]
print("\nDeleting character at 2nd Index: ")
print(String2)
Output:
Initial String:
Hello, I'm a Geek
Deleting character at 2nd Index:
Helo, I'm a Geek
Deletion of the entire string is possible with the use of del keyword. Further, if we
try to print the string, this will produce an error because the String is deleted and is
unavailable to be printed.
Python3
# Deleting a String
# with the use of del
del String1
print("\nDeleting entire String: ")
print(String1)
Error:
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
Traceback (most recent call last):
File "/home/e4b8f2170f140da99d2fe57d9d8c6a94.py", line 12, in
print(String1)
NameError: name 'String1' is not defined
Escape sequences start with a backslash and can be interpreted differently. If single
quotes are used to represent a string, then all the single quotes present in the string
must be escaped and the same is done for Double Quotes.
Example:
Python3
# Initial String
String1 = '''I'm a "Geek"'''
print("Initial String with use of Triple Quotes: ")
print(String1)
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
print(String1)
Output:
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
Example:
To ignore the escape sequences in a String, r or R is used, this implies that the
string is a raw string and escape sequences inside it are to be ignored.
Python3
Output:
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
Printing Raw String in HEX Format:
This is \x47\x65\x65\x6b\x73 in \x48\x45\x58
Formatting of Strings
Strings in Python can be formatted with the use of format() method which is a very
versatile and powerful tool for formatting Strings. Format method in String contains
curly braces {} as placeholders which can hold arguments according to position or
keyword to specify the order.
Example 1:
In this example, we will declare a string which contains the curly braces {} that acts
as a placeholders and provide them values to see how string declaration position
matters.
Python3
# Default order
String1 = "{} {} {}".format('Geeks', 'For', 'Life')
print("Print String in default order: ")
print(String1)
# Positional Formatting
String1 = "{1} {0} {2}".format('Geeks', 'For', 'Life')
print("\nPrint String in Positional order: ")
print(String1)
# Keyword Formatting
String1 = "{l} {f} {g}".format(g='Geeks', f='For', l='Life')
print("\nPrint String in order of Keywords: ")
print(String1)
Output:
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
Print String in default order:
Geeks For Life
Print String in Positional order:
For Geeks Life
Print String in order of Keywords:
Life For Geeks
Example 2:
Integers such as Binary, hexadecimal, etc., and floats can be rounded or displayed in
the exponent form with the use of format specifiers.
Python3
# Formatting of Integers
String1 = "{0:b}".format(16)
print("\nBinary representation of 16 is ")
print(String1)
# Formatting of Floats
String1 = "{0:e}".format(165.6458)
print("\nExponent representation of 165.6458 is ")
print(String1)
Output:
Binary representation of 16 is
10000
Exponent representation of 165.6458 is
1.656458e+02
one-sixth is :
0.17
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
Example 3:
A string can be left, right, or center aligned with the use of format specifiers,
separated by a colon(:). The (<) indicates that the string should be aligned to the left,
(>) indicates that the string should be aligned to the right and (^) indicates that the
string should be aligned to the center. We can also specify the length in which it
should be aligned. For example, (<10) means that the string should be aligned to the
left within a field of width of 10 characters.
Python3
# String alignment
String1 = "|{:<10}|{:^10}|{:>10}|".format('Geeks',
'for',
'Geeks')
print("\nLeft, center and right alignment with Formatting: ")
print(String1)
Output:
Example 4:
Old-style formatting was done without the use of the format method by
using the % operator
Python3
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
# of Integers
Integer1 = 12.3456789
print("Formatting in 3.2f format: ")
print('The value of Integer1 is %3.2f' % Integer1)
print("\nFormatting in 3.4f format: ")
print('The value of Integer1 is %3.4f' % Integer1)
Output:
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
Built-In Function Description
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
Built-In Function Description
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
Built-In Function Description
alphanumeric.
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
Built-In Function Description
Return a list of the words of the string when only used with
string.splitfields
two arguments.
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
Built-In Function Description
removed.
string.rstrip Return a copy of the string with trailing white spaces removed.
string.swapcase Converts lower case letters to upper case and vice versa.
Pad a numeric string on the left with zero digits until the given
string-zfill
width is reached.
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
Built-In Function Description
Strings are used at a larger scale i.e. for a wide areas of operations such as
storing and manipulating text data, representing names, addresses, and other
types of data that can be represented as text.
Python has a rich set of string methods that allow you to manipulate and work
with strings in a variety of ways. These methods make it easy to perform
common tasks such as converting strings to uppercase or lowercase, replacing
substrings, and splitting strings into lists.
Strings are immutable, meaning that once you have created a string, you cannot
change it. This can be beneficial in certain situations because it means that you
can be confident that the value of a string will not change unexpectedly.
Python has built-in support for strings, which means that you do not need to
import any additional libraries or modules to work with strings. This makes it
easy to get started with strings and reduces the complexity of your code.
Python has a concise syntax for creating and manipulating strings, which makes
it easy to write and read code that works with strings.
When we are dealing with large text data, strings can be inefficient. For
instance, if you need to perform a large number of operations on a string, such as
replacing substrings or splitting the string into multiple substrings, it can be slow
and consume a lot resources.
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
Strings can be difficult to work with when you need to represent complex data
structures, such as lists or dictionaries. In these cases, it may be more efficient to
use a different data type, such as a list or a dictionary, to represent the data.
In Order to access the keys randomly in shelve in Python, we have to take three
steps:
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
# now, we simply close the shelf file.
shfile.close()
Output :
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
var = shelve.open("shelf_file", writeback = True)
for x in range(val1):
var['book_list'].append(val)
Input :
Output :
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
['bared_to_you', 'The_fault_in_our_stars', 'The_boy_who_never_let_her_go',
'Hush', 'Knock-Knock']
Note : Input and Output depend upon user, user can update anything in a file which
user want according to user input, output will be changed.
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
Cross-platform: Python file-handling functions work across different platforms
(e.g. Windows, Mac, Linux), allowing for seamless integration and
compatibility.
Hello world
GeeksforGeeks
123 456
f = open(filename, mode)
Where the following mode is supported:
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
2. w: open an existing file for a write operation. If the file already contains some
data then it will be overridden but if the file is not present then it creates the file
as well.
3. a: open an existing file for append operation. It won’t override existing data.
4. r+: To read and write data into the file. The previous data in the file will be
overridden.
5. w+: To write and read data. It will override existing data.
6. a+: To append and read data from the file. It won’t override existing data.
There is more than one way to read a file in Python . Let us see how we can read the
content of a file in read mode.
Example 1: The open command will open the file in the read mode and the for loop
will print each line present in the file.
Python3
Output:
Hello world
GeeksforGeeks
123 456
Example 2: In this example, we will extract a string that contains all characters in
the file then we can use file.read().
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
Python3
Output:
Hello world
GeeksforGeeks
123 456
Example 3: In this example, we will see how we can read a file using the with
statement.
Python3
print(data)
Output:
Hello world
GeeksforGeeks
123 456
Example 4: Another way to read a file is to call a certain number of characters like
in the following code the interpreter will read the first five characters of stored data
and return it as a string:
Python3
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
Output:
Hello
Example 5:
We can also split lines while reading files in Python. The split() function splits the
variable when space is encountered. You can also split using any characters as you
wish.
Python3
Output:
['Hello', 'world']
['GeeksforGeeks']
['123', '456']
Let’s see how to create a file and how the write mode works.
Example 1: In this example, we will see how the write mode and the write()
function is used to write in a file. The close() command terminates all the resources
in use and frees the system of this particular program.
Python3
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
# Python code to create a file
file = open('geek.txt','w')
file.write("This is the write command")
file.write("It allows us to write in a particular file")
file.close()
Output:
Example 2: We can also use the written statement along with the with() function.
Python3
Output:
Hello World!!!
Example: For this example, we will use the file created in the previous example.
Python3
Output:
This is the write commandIt allows us to write in a particular fileThis will add this
line
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
There are also various other commands in file handling that are used to handle
various tasks:
rstrip(): This function strips each line of a file off spaces from the right-hand side.
lstrip(): This function strips each line of a file off spaces from the left-hand side.
It is designed to provide much cleaner syntax and exception handling when you are
working with code. That explains why it’s good practice to use them with a
statement where applicable. This is helpful because using this method any files
opened will be closed automatically after one is done, so auto-cleanup.
In this example, we will cover all the concepts that we have seen above. Other than
those, we will also see how we can delete a file using the remove() function from
Python os module.
Python3
import os
def create_file(filename):
try:
with open(filename, 'w') as f:
f.write('Hello, world!\n')
print("File " + filename + " created successfully.")
except IOError:
print("Error: could not create file " + filename)
def read_file(filename):
try:
with open(filename, 'r') as f:
contents = f.read()
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
print(contents)
except IOError:
print("Error: could not read file " + filename)
def delete_file(filename):
try:
os.remove(filename)
print("File " + filename + " deleted successfully.")
except IOError:
print("Error: could not delete file " + filename)
if __name__ == '__main__':
filename = "example.txt"
new_filename = "new_example.txt"
create_file(filename)
read_file(filename)
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
append_file(filename, "This is some additional text.\n")
read_file(filename)
rename_file(filename, new_filename)
read_file(new_filename)
delete_file(new_filename)
Output:
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
data has to be read or written in the file. There are 6 access
modes in python.
1. Read Only (‘r’) : Open text file for reading. The handle is
positioned at the beginning of the file. If the file does not
exists, raises the I/O error. This is also the default mode in
which a file is opened.
2. Read and Write (‘r+’): Open the file for reading and
writing. The handle is positioned at the beginning of the file.
Raises I/O error if the file does not exist.
3. Write Only (‘w’) : Open the file for writing. For the existing
files, the data is truncated and over-written. The handle is
positioned at the beginning of the file. Creates the file if the
file does not exist.
4. Write and Read (‘w+’) : Open the file for reading and
writing. For an existing file, data is truncated and over-
written. The handle is positioned at the beginning of the file.
5. Append Only (‘a’): Open the file for writing. The file is
created if it does not exist. The handle is positioned at the
end of the file. The data being written will be inserted at the
end, after the existing data.
6. Append and Read (‘a+’) : Open the file for reading and
writing. The file is created if it does not exist. The handle is
positioned at the end of the file. The data being written will
be inserted at the end, after the existing data.
How Files are Loaded into Primary
Memory
There are two kinds of memory in a computer i.e. Primary and
Secondary memory every file that you saved or anyone saved is
on secondary memory cause any data in primary memory is
deleted when the computer is powered off. So when you need to
change any text file or just to work with them in python you
need to load that file into primary memory. Python interacts with
files loaded in primary memory or main memory through “file
handlers” ( This is how your operating system gives access to
python to interact with the file you opened by searching the file
in its memory if found it returns a file handler and then you can
work with the file ).
Opening a File
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
The file should exist in the same directory as the python
program file else, the full address of the file should be written in
place of the filename. Note: The r is placed before the filename
to prevent the characters in the filename string to be treated as
special characters. For example, if there is \temp in the file
address, then \t is treated as the tab character, and an error is
raised of invalid address. The r makes the string raw, that is, it
tells that the string is without any special characters. The r can
be ignored if the file is in the same directory and the address is
not being placed.
Python
# Open function to open the file
"MyFile1.txt"
# (same directory) in append mode and
file1 = open("MyFile1.txt","a")
Closing a file
close() function closes the file and frees the memory space
acquired by that file. It is used at the time when the file is no
longer needed or if it is to be opened in a different file mode.
File_object.close()
Python
# Opening and Closing a file
"MyFile.txt"
# for object name file1.
file1 = open("MyFile.txt","a")
file1.close()
Writing to a file
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
1. writelines() : For a list of string elements, each string is
inserted in the text file.Used to insert multiple strings at a
single time.
File_object.writelines(L) for L = [str1, str2, str3]
Python3
# Program to show various ways to read and
# write data in a file.
file1 = open("myfile.txt","w")
L = ["This is Delhi \n","This is Paris \n","This is
London \n"]
file1 = open("myfile.txt","r+")
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
file1.seek(0)
file1.seek(0)
file1.seek(0)
# readlines function
print("Output of Readlines function is ")
print(file1.readlines())
print()
file1.close()
Output:
Output of Read function is
Hello
This is Delhi
This is Paris
This is London
Output of Readline function is
Hello
Output of Read(9) function is
Hello
Th
Output of Readline(9) function is
Hello
Output of Readlines function is
['Hello \n', 'This is Delhi \n', 'This is Paris \n',
'This is London \n']
Appending to a file
Python3
# Python program to illustrate
# Append vs write mode
file1 = open("myfile.txt","w")
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
L = ["This is Delhi \n","This is Paris \n","This is
London \n"]
file1.writelines(L)
file1.close()
# Append-adds at last
file1 = open("myfile.txt","a")#append mode
file1.write("Today \n")
file1.close()
file1 = open("myfile.txt","r")
print("Output of Readlines after appending")
print(file1.readlines())
print()
file1.close()
# Write-Overwrites
file1 = open("myfile.txt","w")#write mode
file1.write("Tomorrow \n")
file1.close()
file1 = open("myfile.txt","r")
print("Output of Readlines after writing")
print(file1.readlines())
print()
file1.close()
Output:
Output of Readlines after appending
['This is Delhi \n', 'This is Paris \n', 'This is London
\n', 'Today \n']
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
Generally, binary means two. In computer science, binary files
are stored in a binary format having digits 0’s and 1’s. For
example, the number 9 in binary format is represented as
‘1001’. In this way, our computer stores each and every file in a
machine-readable format in a sequence of binary digits. The
structure and format of binary files depend on the type of file.
Image files have different structures when compared to audio
files. However, decoding binary files depends on the complexity
of the file format. In this article, let’s understand the reading of
binary files.
Python3
# Opening the binary file in binary mode as r
f = open("files.zip", mode="rb")
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
Output:
In the output, we see a sequence of byte data as bytes are the
fundamental unit of binary representation.
b’PK\x03\x04\x14\x00\x00\x00\x08\x00U\xbd\xebV\
xc2=j\x87\x1e\x00\x00\x00!\x00\x00\x00\n\x00\x00\
x00TODO11.txt\xe3\xe5JN,\xceH-/\xe6\xe5\x82\xc0\
xcc\xbc\x92\xd4\x9c\x9c\xcc\x82\xc4\xc4\x12^.w7w\
x00PK\x01\x02\x14\x00\x14\x00\x00\x00\x08\x00U\
xbd\xebV\xc2=j\x87\x1e\x00\x00\x00!\x00\x00\x00\
n\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\x00\
x00\x00\x00\x00\x00TODO11.txtPK\x05\x06\x00\x00\
x00\x00\x01\x00\x01\x008\x00\x00\x00F\x00\x00\
x00\x00\x00′
Python3
# Open the binary file
file = open("string.bin",
"rb")
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
This line reads the first three bytes from the binary file and
stores them in the variable “data”. The “read(3)” method bytes
from the file and advance the pointer accordingly.
Python3
data =
file.read(3)
Python3
while data:
print(data)
data =
file.read(3)
Python3
file.close(
)
Python
# Open the binary file
file = open("string.bin", "rb")
# Reading the first three bytes from the binary
file
data = file.read(3)
# Printing data by iterating with while loop
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
while data:
print(data)
data = file.read(3)
# Close the binary file
file.close()
Python3
# Specify the size of each chunk to read
chunk_size = 10
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
example, if the file contains the binary data “b” Hello, this is
binary data!’, and the chunk_size is set to 10, the output will be:
Output :
Read 10 bytes: b'Hello, thi'
Read 10 bytes: b's is binar'
Read 7 bytes: b'y data!'
To read a binary file into an array.bin and used the “wb” mode
to write a given binary file. The “array” is the name of the file.
assigned array as num=[3,6,9,12,18] to get the array in byte
format. use byte array().
To write an array to the file we use:
Python3
file=open("array","wb"
)
num=[3,6,9,12,18]
array=bytearray(num)
file.write(array)
file.close()
To read the written array from the given file, we have used the
same file i.e., file=open(“array”, “rb”). rb used to read the array
from the file. The list() is used to create a list object.
number=list(file. read(3)). To read the bytes from the file. read()
is used.
Python3
file=open("array","rb")
number=list(file.read(3
))
print (number)
file.close()
Output:
[3,6,9]
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
To read a binary file into a NumPy array, import module NumPy.
The “dtype” is “np.unit8” which stands for “unsigned 8-bit
integer” This means that each item in the array is an 8-bit (1
byte) integer, with values that can range from 0 to 255.
Python3
import numpy as np
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
Python3
from dbmodule import connect
# Run queries
cursor.execute('select * from mytable')
results = cursor.fetchall()
# Free resources
cursor.close()
connection.close()
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
parameters that are the database name, username, and
password. The connect function returns the connection
object.
2. After this, we create a cursor object on the connection
object. The cursor is used to run queries and get the results.
3. After running the queries using the cursor, we also use the
cursor to fetch the results of the query.
4. Finally, when the system is done running the queries, it frees
all resources by closing the connection. Remember that it
is always important to close connections to avoid unused
connections taking up resources.
Types of NoSQL database: Types of NoSQL databases and the
name of the database system that falls in that category are:
Graph Databases: Examples – Amazon Neptune, Neo4j
1.
Key value store: Examples – Memcached, Redis, Coherence
2.
Column: Examples – Hbase, Big Table, Accumulo
3.
Document-based: Examples – MongoDB, CouchDB,
4.
Cloudant
When should NoSQL be used:
1. When a huge amount of data needs to be stored and
retrieved.
2. The relationship between the data you store is not that
important
3. The data changes over time and is not structured.
4. Support of Constraints and Joins is not required at the
database level
5. The data is growing continuously and you need to scale the
database regularly to handle the data.
In conclusion, NoSQL databases offer several benefits over
traditional relational databases, such as scalability, flexibility,
and cost-effectiveness. However, they also have several
drawbacks, such as a lack of standardization, lack of ACID
compliance, and lack of support for complex queries. When
choosing a database for a specific application, it is important to
weigh the benefits and drawbacks carefully to determine the
best fit.
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
Getting initial Response
The get() method is used to get the basic information of the
resources used at the server-side. This function fetches the data
from the server and returns as a response object which can be
printed in a simple text format.
Python3
# Import libraries
import requests
# Sending Request
req =
requests.get('https://www.geeksforgeeks.org/')
# Show results
print(req.text[:2000])
Output:
Getting session-info
The session() method returns the session object which provides
certain parameters to manipulate the requests. It can also
manipulate cookies for all the requests initiated from the session
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
object. If a large amount of requests are made to a single host
then, the associated TCP connection is recalled.
Python3
# Import Libraries
import requests
# Creating Session
s = requests.Session()
s.get('http://httpbin.org/cookies/set/sessioncookie/
419735271')
# Getting Response
r = s.get('http://httpbin.org/cookies')
# Show Response
print(r.text)
Output:
{
"cookies": {
"sessioncookie": "419735271"
}
}
Error Handling
If some error is raised in processing the request to the server,
the exception is raised by the program which can be handled
using the timeout attribute, which defines the time value until
the program waits and after that, it raises the timeout error.
Python3
# Import Libraries
import requests
# Error Handling
try:
# Creating Request
req = requests.get('https://www.geeksforgeeks.org/',
timeout=0.000001)
except requests.exceptions.RequestException as e:
# Raising Error
raise SystemExit(e)
Output:
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
HTTPSConnectionPool(host=’www.geeksforgeeks.org’
, port=443): Max retries exceeded with url: / (Caused
by
ConnectTimeoutError(<urllib3.connection.HTTPSConn
ection object at 0x0000018CFDAD83C8>,
‘Connection to www.geeksforgeeks.org timed out.
(connect timeout=1e-06)’))
Gunicorn
Gunicorn is a stand-alone web server which has a central
master process tasked with managing the initiated worker
processes of differing types. These worker processes then
handle and deal with the requests directly. And all this can
be configured and adapted to suit the diverse needs of
production scenarios.
Important Features
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
CherryPy is a self contained web framework as it can run on
its own without the need of additional software. It has its
own WSGI, HTTP/1.1-compliant web server. As it is a WSGI
server, it can be used to serve any other WSGI Python
application as well, without being bound to CherryPy's
application development framework.
Important Features
Twisted Web
It is a web server that comes with the Twisted networking
library. Whereas Twisted itself is "an event-driven
networking engine", the Twisted Web server runs on WSGI
and it is capable of powering other Python web applications.
Important Features
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
A web service is any piece of software that makes itself
available over the internet and uses a standardized
XML messaging system. XML is used to encode all
communications to a web service. For example, a client
invokes a web service by sending an XML message,
then waits for a corresponding XML response. As all
communication is in XML, web services are not tied to
any one operating system or programming language—
Java can talk with Perl; Windows applications can talk
with Unix applications.
Web services are self-contained, modular, distributed,
dynamic applications that can be described, published,
located, or invoked over the network to create
products, processes, and supply chains. These
applications can be local, distributed, or web-based.
Web services are built on top of open standards such
as TCP/IP, HTTP, Java, HTML, and XML.
Web services are XML-based information exchange
systems that use the Internet for direct application-to-
application interaction. These systems can include
programs, objects, messages, or documents.
A web service is a collection of open protocols and
standards used for exchanging data between
applications or systems. Software applications written
in various programming languages and running on
various platforms can use web services to exchange
data over computer networks like the Internet in a
manner similar to inter-process communication on a
single computer. This interoperability (e.g., between
Java and Python, or Windows and Linux applications) is
due to the use of open standards.
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
Uses a standardized XML messaging system
Is not tied to any one operating system or
programming language
Is self-describing via a common XML grammar
Is discoverable via a simple find mechanism
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
You can build a Java-based web service on Solaris that is
accessible from your Visual Basic program that runs on
Windows.
Example
Consider a simple account-management and order
processing system. The accounting personnel use a client
application built with Visual Basic or JSP to create new
accounts and enter new customer orders.
R.JAYAPRABA M.C.A.,M.PHIL
PYTHON PROGRAMMING
UNIT-4
R.JAYAPRABA M.C.A.,M.PHIL