PYTHON
PYTHON
BCA-III
SOUNotes
SOUNotes
UNIT-01 Overview of
Python
Introduction
Python is a simple, easy to learn, high-level, interpretive, general-purpose, free and
open source, and Powerful programming language.
It has efficient high-level data structures and a simple but effective approach to
object-oriented programming.
Python was introduced in the late 1980s and its implementation was started in
December 1989 by Dutch programmer Guido van Rossum at CWI (Centrum
Wiskunde & Informatica) Research lab in the Netherlands.
Python based on ABC, C, Bourne Shell, Modula-3, Perl, Haskell, and Lisp
Named after Guido's favourite BBC comedy TV show "Monty Python's Flying Circus"
3
with no copyright issues.
6. Object-Oriented Language:
Python supports object-oriented style of programming (OOP) that encapsulates
the code within objects.
OOP is a modern programming paradigm that is based on the concepts of classes
and objects.
It breaks up the code into several segments that messages back and forth using
classes.
Object-oriented programming supports inheritance, polymorphism, data
encapsulation, inheritance, polymorphism, etc.
Its procedure helps to programmer to write reusable code and develop powerful
applications in less code with a good level of abstraction.
7. Interactive:
Python is really interactive, so we can write a program directly on the Python
prompt.
The advantage of being Python interactive is we can interact directly with the
interpreter and get the immediate results.
We can also use the prompt to test out small bits of codes to see if they work
8. Easy to Maintain:
We can easily maintain the source code of Python programming language.
9. Extensible Feature:
We can integrate Python with other languages such as C, C++, and Java.
It allows us to execute the code written in other programming languages. This
implies that we can compile the code in other languages like C/C++, or Java, and
then can use that in our python code, which we can compile and run anywhere
10. High-Level Language:
Python is a high-level programming language, which means it enables the
programmer to write programs that are not specific to a particular type of
computer or designed for a specific task.
A high-level programming language is easier to write and understand.
Programmers can easily write and understand or interpret the code.
It is closer to human language and far to machine language.
For a computer to understand and run a program designed with a high-level
language, we must compile it into machine language.
11. Broad Standard Library:
One of the main reasons for Python's popularity is its large standard library for
the various fields such as machine learning, data science, web developer, and also
for the scripting.
Python contains a rich set of modules and functions that are cross-platform.
Web Development Libraries: Django, Flask, Bottle, Tornado, Pyramid, web2py,
CherryPy, CubicWeb
GUI Development Libraries: Tkinter, Libavg, PyGObject, PySimpleGUI, PyQt,
PySide, Kivy, wxPython, PyForms
4
Scientific and Numeric Libraries: SciPy, Numpy, Pandas, IPython, TensorFlow,
Seaborn, Matplotlib
12. Dynamic Typed Language:
Python is a dynamically typed language.
This means that the Python interpreter does type checking of variable at the
runtime.
Interpreter assigns the type of variable based on the value of variable at the
runtime.
We don't declare the data type of a variable explicitly in Python.
Interpreter decides the data type of variable and its memory allocation at
runtime.
Interpreter automatically allocates the memory to the variable at runtime when
we assign a value to the variable.
13. GUI Programming Support:
Python provides many graphical user interface (GUI) libraries that are used for
the developing Desktop web application.
14. Databases Support:
When we develop an application, we may need a database.
Python language provides Python Database API (DB-API) that provides an
interface to all major commercial databases.
MySQL, PostgreSQL, Microsoft SQL, Oracle, Informix, etc. are some databases
supported by standard python.
To use it, just import the interface for the particular database.
Using Python, we can work with both relational and non-relational databases.
15. Automation Tool:
Python is a great tool for the automation process.
We can write simple Python programs to automate routine tasks, such as
repetitive or time-consuming.
16. Scalable:
This feature of Python provides a better structure and supports for large
programs.
Limitations of Python
Python is an interpreter-based language. Therefore, it is slower in the terms of
execution of programs as compared to other programming languages
As we know python is a high-level language, it also uses several layers to
communicate with the operating system and computer hardware
Graphics applications such as video games make the program to run slower.
What is an Interpreter
An interpreter is simple software that executes the source code line by line
5
An interpreter is a program/software that converts a programming language into
Machine language that a computer can understand and execute.
While Interpreting a code, an interpreter will report any error it finds in the code. If it
does not find any error it will translate the code into Machine language.
The Python interpreter's name is CPython. It is written in C Language.
print() Function
The print() function prints the specified message to the screen, or other standard
output device.
The message can be a string, or any other object, the object will be converted into a
string before written to the screen.
Syntax: print(object(s), sep=separator, end=end, file=file, flush=flush)
print("Hello World!")
print(22+44)
Parameter Values:
Parameter Description
object(s) Any object, and as many as you like. Will be converted to string before
printed
sep = Specify how to separate the objects, if there is more than one. Default
'separator' is ' ' (Optional)
end='end' Specify what to print at the end. Default is '\n' (line feed) (Optional)
file An object with a write method. Default is sys.std out (Optional)
flush A Boolean, specifying if the output is flushed (True) or buffered (False).
Default is False (Optional)
6
1. Documentation section:
The documentation section consists of a set of comment lines giving the name of
the program, the author, and other details, which the programmer would like to
use later.
2. Imports:
The imports section provides instructions to the interpreter to link functions from
the module such as using the import statement.
3. Global variables section:
Some variables are used in more than one function.
Such variables and are declared in the global declaration section that is outside of
all the functions.
4. Class definitions:
Here, we can declare different classes.
Classes are a collection of data members and data functions.
5. User-defined functions:
This section also declares all the user-defined functions.
6. Executable part:
There is at least one statement in the executable part.
# Documentation Section
# Write a Program to show use of scope variable using function
# Import Section
import math
# Executable Part
p1 = Person("John", "19")
p2 = Person("Alex", "20")
7
p1.greet()
p2.greet()
Keywords
Keywords are reserved words that cannot be used as a variable name, function name, or
any other identifier.
Keyword Description
and A logical operator
as To create an alias
assert For debugging
break To break out of a loop
class To define a class
continue To continue to the next iteration of a loop
def To define a function
del To delete an object
elif Used in conditional statements, same as else if
else Used in conditional statements
except Used with exceptions, what to do when an exception occurs
False Boolean value, result of comparison operations
finally Used with exceptions, a block of code that will be executed no matter if there
is an exception or not
for To create a for loop
from To import specific parts of a module
global To declare a global variable
if To make a conditional statement
import To import a module
in To check if a value is present in a list, tuple, etc.
is To test if two variables are equal
lambda To create an anonymous function
None Represents a null value
nonlocal To declare a non-local variable
not A logical operator
or A logical operator
pass A null statement, a statement that will do nothing
raise To raise an exception
return To exit a function and return a value
True Boolean value, result of comparison operations
try To make a try...except statement
8
Keyword Description
while To create a while loop
with Used to simplify exception handling
yield To end a function, returns a generator
Identifiers
Identifier is a user-defined name given to a variable, function, class, module, etc.
They are case-sensitive
It is a good programming practice to give meaningful names to identifiers to make
the code understandable.
We can also use the isidentifier() method to check whether a string is a valid
identifier or not.
Variables
Variable is containers that store values.
Python is not statically typed.
We do not need to declare variables before using them or declare their type.
A variable is created the moment we first assign a value to it.
num = 12
Variable names can be any length can have capitalized, lowercase (start to finish, a to
z), the digit (0-9), and highlight character( _ ).
Local Variable: The variables that are declared within the function and have scope
within the function are known as local variables.
def add():
a = 15
b = 25
c = a+b
print(c)
9
add()
print(c)
# Output
40
ERROR!
Traceback (most recent call last):
File "<main.py>", line 10, in <module>
NameError: name 'c' is not defined
Global Variables: The variables that are declared globally and have scope in entire
program known as Global variables.
def add():
c = a+b
print(c) # Local Variable
print(c)
# Output: 40
age = 19
temp = 10
temp = "Hello"
temp = False
del temp
print(temp) # ERROR: name 'temp' is not defined
User Input
10
By default input() takes values as String type.
print(name)
print(age)
Data Types
In Python, the int data type is a numeric type used to represent whole integer
number as opposition with float number.
Creating a int is done by using the whole integer number without quotes or using
the int() constructor function
In Python, the float data type is a numeric type that is used to represent number
with floating point values as opposition with whole int number.
Creating a float is done by using the number using the decimal point ( . ) without
quotes or using the float() constructor function.
In Python, the complex data type represents complex numbers that contain a real
part and an imaginary part. In complex numbers, the real part and the imaginary part
are floating-point numbers denoted by the suffix “j” or “J”.
Complex numbers are used often in mathematical and scientific calculations.
11
# int Type
i = 3
print(type(i)) # <class 'int'>
# float Type
f = 3.1
print(type(f)) # <class 'float'>
# complex Type
z = 2 + 5j # Real part: 2, imaginary part: 5
print(type(z)) # <class 'complex'>
In Python, the bool data type is used to represent Boolean values ( True , False ).
Booleans are used to evaluate expressions and return the
Boolean True or False based on the result of the expression.
# Boolean expression
x = 10
y = 5
result = x > y
print(result) # True
print(type(result)) # <class 'bool'>
In Python, the str data type is used to define text component enclosing a sequence
of characters within single-quotes or double-quotes. Python strings can contain
letters, numbers or special characters.
# Print string
print(greet)
In Python, the list data type is used to store ordered sequence of elements. Python
lists are ordered collections that can contain elements of various data types (str, list,
dicts, …). List elements can be accessed, iterated, and removed.
Slicing or accessing elements of a list is done using the square brackets ( [] ) notation.
Creating a list is done using the square brackets ( [] ) or the list() constructor
function
12
ls = ['hello', 1, True, [1, 2]]
In Python, Tuples are a data structure of the sequence type that store a collection of
data.
Python Tuples have these 5 characteristics.
ordered
unchangeable
immutable
allow duplicate value
allow values with multiple data types
Creating a tuple is done using the parentheses ( () ) or the tuple() constructor
function.
t = (1, 2, 3, 4, 5)
print(t) # (1, 2, 3, 4, 5)
print(type(t)) # <class 'tuple'>
d = {
'name': 'John',
'last_name': 'Doe'
}
In Python, sets are an unordered collection unique elements (no duplicate values). A
Python set is a mutable object where you can add, remove, or modify elements after
creating it.
13
Creating a set is done adding comma-separated values inside curly brackets ( {} ) or
using the set() constructor function.
Python Sets have a multiple characteristics:
Duplicates are not allowed
They can have Multiple data Types
Sets Can’t Be Accessed with the Index
Not Subscriptable
s = {1,2,3}
print(s) # {1, 2, 3}
print(type(s)) # <class 'set'>
# set
my_set = {1, 2, 3, 4}
my_set.add(5)
my_set.remove(2)
print(my_set) # {1, 3, 4, 5}
# frozenset
my_frozenset = frozenset([1, 2, 3, 4])
Operators
Arithmetic Operators
14
Operator Meaning Example
% Modulus – remainder of the division of left operand by x % y (remainder
the right of x/y)
// Floor division – division that results into whole number x // y
adjusted to the left in the number line
** Exponent – left operand raised to the power of right x**y (x to the
power y)
Assignment Operator
Comparison Operator
15
Operator Meaning Example
> Greater that – True if left operand is greater than the right x>y
< Less that – True if left operand is less than the right x<y
== Equal to – True if both operands are equal x == y
!= Not equal to – True if operands are not equal x != y
>= Greater than or equal to – True if left operand is greater than or x >= y
equal to the right
<= Less than or equal to – True if left operand is less than or equal to x <= y
the right
Logical Operators
Bitwise Operator
Membership Operator
Operator Meaning
in Evaluates to true if it finds a variable in the specified sequence and false
otherwise.
not in Evaluates to true if it does not finds a variable in the specified sequence and
false otherwise.
Identity Operator
16
Operator Meaning
is Evaluates to true if the variables on either side of the operator point to the
same object and false otherwise.
not is Evaluates to false if the variables on either side of the operator point to the
same object and true otherwise.
Operator Precedence
Operators Description
() Parentheses (grouping)
** Exponentiation (raise to the power)
~+ – Complement, unary plus and minus (method names for the last
two are +@ and -@)
*/ % // Multiply, divide, modulo and floor division
+– Addition and subtraction
>> << Right and left bitwise shift
& Bitwise ‘AND’
^| Bitwise exclusive OR’ and regular OR’
<= < > >= Comparison operators
< > == != Equality operators
= %= /= //= -= += Assignment operators
*= **=
is, is not Identity operators
in, not in Membership operators
not or and Logical operators
Type Conversion
The act of changing an object's data type is known as type conversion.
The Python interpreter automatically performs Implicit Type Conversion.
Python prevents Implicit Type Conversion from losing data.
The user converts the data types of objects using specified functions in explicit type
conversion, sometimes referred to as type casting.
When type casting, data loss could happen if the object is forced to conform to a
particular data type.
Implicit Type Conversion: In Implicit type conversion of data types in Python, the
Python interpreter automatically converts one data type to another without any user
involvement.
Explicit Type Conversion: The data type is manually changed by the user as per their
requirement. With explicit type conversion, there is a risk of data loss since we are
17
forcing an expression to be changed in some specific data type.
celcius = 25
fahrenheit = (celcius*9/5)+32 # int -> float
print(fahrenheit) # 77.0
num = 15
number = str(num) # int -> string
print(number) # 15
Conditional Statements
if Statement
num = 15
if (num%2 == 0):
print("Number is Even)
if-else Statement
We can use the else statement with the if statement Python to execute a block of
code when the Python if condition is false
num = 15
if (num%2 == 0):
print("Number is Even)
else:
print("number is Odd)
elif Statement
As soon as one of the conditions controlling the if is true, the statement associated
with that if is executed, and the rest of the ladder is bypassed.
If none of the conditions is true, then the final “else” statement will be executed.
mark = 87
if mark>=90:
18
print("Grade: A")
elif mark >= 75:
print("Grade: B")
elif mark >= 60:
print("Grade: C")
elif mark >= 40:
print("Grade: D")
else:
print("Fail)
if x > y:
print("x is greater than y")
elif x < y:
print("x is less than y")
else:
if x == y:
print("x is equal to y")
else:
print("This should never happen")
Loop
for Loop
A for loop is used for iterating over a sequence (that is either a list, a tuple, a
dictionary, a set, or a string).
With the for loop we can execute a set of statements, once for each item in a list,
tuple, set etc
num = 5
19
while Loop
While loops are used in Python to iterate until a specified condition is met.
However, the statement in the program that follows the while loop is executed once
the condition changes to false
num = 5
i = 1
while(i<=10):
print(num, "x", i, " = ", num*i)
i += 1
This command skips the current iteration of the loop. The statements following the
continue statement are not executed once the Python interpreter reaches the continue
statement.
break Statement
20
This command terminates the loop's execution and transfers the program's control to
the statement next to the loop.
pass Statement
The pass statement is used when a statement is syntactically necessary, but no code
is to be executed.
for i in range(5):
pass # Loop does nothing
21
UNIT-02 String, Lists &
Functions
String
Creating and Storing Strings
In Python, strings can be created using single quotes ( ' ) or double quotes ( " ). They
are immutable sequences of characters.
String Methods
23
Python provides many built-in methods for manipulating strings, such as upper() ,
lower() , strip() , replace() , split() , etc.
Formatting Strings
String formatting allows you to interpolate variables and expressions within strings.
Python supports multiple ways of string formatting, including f-strings, str.format() ,
and % formatting.
Lists
Creating Lists
Lists are one of Python's built-in data types used to store multiple items in a single
variable. Lists are ordered, mutable, and can contain items of different data types.
24
You can access individual elements or slices of a list using indexing and slicing.
Indexing starts at 0, and slicing uses the list[start:end:step] syntax.
# Slicing
print(my_list[1:4]) # Output: [20, 30, 40]
print(my_list[::2]) # Output: [10, 30, 50]
List Methods
Python provides several useful methods for lists, such as append() , extend() ,
insert() , remove() , pop() , reverse() , and sort() .
25
my_list.reverse() # Reverses the list
print(my_list) # Output: [30, 15, 10]
Functions
Built-in Functions
Python comes with several built-in functions for various operations, such as print() ,
len() , type() , range() , input() , etc. These functions are always available and don't
require any imports.
26
import datetime
result = add(5, 3)
print(result) # Output: 8
my_function() # Output: 10
27
print(global_var) # Output: 20
modify_global()
print(global_var) # Output: 50
Default Parameters
You can provide default values to function parameters. If the caller doesn't pass a
value, the default will be used.
Keyword Arguments
Python allows you to call functions using keyword arguments, where the name of the
argument is explicitly mentioned, making the function calls more readable.
def print_arguments():
print("Command Line Arguments:", sys.argv)
Questions
28
1. What is a string in Python? Explain string operations with an example.
2. What is string slicing? Provide an example and explain how slicing can be used to
reverse a string.
3. List five methods of string manipulation in Python.
4. What is a list in Python? Explain list operations with examples.
5. Describe the list method in Python with an example.
6. Differentiate between a list and a string in Python.
7. What is a function in Python? Explain any five built-in functions in Python.
8. Explain the concept of scope and lifetime of variables within a function.
9. What is the purpose of a function? How do you declare a function in Python? explain it
with an example.
29
UNIT-03 Dictionaries,
Tuples & Sets
Dictionaries
Creating Dictionary
A dictionary in Python is a collection of key-value pairs. Each key is associated with a
value, and dictionaries are unordered, mutable, and indexed by keys.
print(person)
# Output: {'name': 'Alice', 'age': 25, 'city': 'New York'}
# Accessing values
print(person["name"]) # Output: Alice
print(person["age"]) # Output: 25
# Modifying values
person["age"] = 26
print(person)
# Output: {'name': 'Alice', 'age': 26, 'city': 'New York'}
Dictionary Methods
Dictionaries come with various methods for performing operations, such as get() ,
keys() , values() , items() , pop() , update() , and more.
# get() method
print(person.get("name")) # Output: Alice
print(person.get("job", "Not available")) # Output: Not available
# pop() method
age = person.pop("age")
print(age) # Output: 25
print(person) # Output: {'name': 'Alice', 'city': 'New York'}
# update() method
person.update({"age": 26, "job": "Engineer"})
print(person) # Output: {'name': 'Alice', 'city': 'New York', 'age':
26, 'job': 'Engineer'}
32
}
Tuples
Creating Tuples
A tuple is an immutable sequence of items. Tuples are created using parentheses ()
and can store different types of data.
# Concatenation
new_tuple = tuple1 + tuple2
print(new_tuple) # Output: (1, 2, 3, 4, 5)
# Repetition
repeated_tuple = tuple1 * 3
print(repeated_tuple) # Output: (1, 2, 3, 1, 2, 3, 1, 2, 3)
# Membership
print(2 in tuple1) # Output: True
print(6 in tuple1) # Output: False
33
# Example of indexing and slicing
my_tuple = (10, 20, 30, 40, 50)
# Indexing
print(my_tuple[0]) # Output: 10
print(my_tuple[-1]) # Output: 50
# Slicing
print(my_tuple[1:4]) # Output: (20, 30, 40)
print(my_tuple[:3]) # Output: (10, 20, 30)
print(len(numbers)) # Output: 4
print(max(numbers)) # Output: 40
print(min(numbers)) # Output: 10
print(sum(numbers)) # Output: 100
34
print(location_coordinates[(40.7128, -74.0060)])
# Output: New York
Tuple Methods
Tuples have only two methods: count() and index() .
# count() method
print(my_tuple.count(20)) # Output: 2
# index() method
print(my_tuple.index(30)) # Output: 3
Sets
Creating Sets
Sets are unordered collections of unique elements. Sets are created using curly braces
{} or the set() constructor.
Set Methods
Sets have several built-in methods like add() , remove() , union() , intersection() ,
and difference() .
35
# Example of set methods
fruits = {"apple", "banana", "cherry"}
# add() method
fruits.add("orange")
print(fruits) # Output: {'apple', 'orange', 'cherry', 'banana'}
# remove() method
fruits.remove("banana")
print(fruits) # Output: {'apple', 'orange', 'cherry'}
# union() method
set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1.union(set2)) # Output: {1, 2, 3, 4, 5}
# intersection() method
print(set1.intersection(set2)) # Output: {3}
# difference() method
print(set1.difference(set2)) # Output: {1, 2}
Traversing of Sets
You can iterate through a set using a for loop, but remember that sets are unordered,
so the elements will not follow any particular sequence.
Questions
1. How to create a dictionary in python? Explain operations of dictionary with example.
2. what is dictionary ? explain any 5 methods of dictionary in python.
3. difference between tuple and set.
4. What is the difference between tuples and lists in Python? Can a tuple be converted
into a list?
5. what is tuple? Explain any three methods of tuple with example.
6. what is set? Explain any three methods of set with example.
7. Discuss the advantages and disadvantages of dictionaries in Python.
36
8. explain list, tuple, set, and dictionary with example.
9. write down any five built in method of dictioanry. Explain each method with example.
37
UNIT-04 File Handling
Introduction
File is a collection of related data stored on a secondary storage device, such as a
hard disk, CD, DVD, pen-drive, etc. A file has a name and extension that indicates its
type.
Files are used to store data permanently and to transfer data between different
programs or devices.
The file handling plays an important role when the data needs to be stored
permanently into the file.
A file is a named location on disk to store related information.
We can access the stored information (non-volatile) after the program termination.
39
That’s because all the binary files will be encoded in the binary format, which can be
understood only by a computer or machine.
For handling such binary files we need a specific type of software to open it.
Text Files
Text files don’t have any specific encoding and it can be opened in normal text editor
itself.
40
file_object = open(file_name, mode)
# File name should also include file's extension
Modes
f = open("demofile.txt", "a")
f = open("demofile.txt", "w")
41
f = open("demofile.txt", "r")
print(f.read())
Advantages Disadvantages
Versatility: Allows a wide range of Error-prone: Operations can lead to errors if
operations (creating, reading, writing, not carefully written or due to file system
appending, renaming, deleting files). issues (e.g., permissions, locks).
Flexibility: Supports different file types Security risks: Can pose security risks if
(text, binary, CSV, etc.) and various user input allows access to sensitive files.
operations (read, write, append).
User-friendly: Provides an easy-to-use Complexity: Can become complex with
interface for creating, reading, and advanced file formats or operations,
manipulating files. requiring careful coding.
Cross-platform: Functions work across Performance: Can be slower than other
different platforms (Windows, Mac, programming languages, especially with
Linux) for seamless integration. large files or complex operations.
Binary Files
A binary file is a file that contains data in the form of bytes, which can represent any
type of data, such as images, audio, video, executable code, etc.
A binary file cannot be read or edited using a text editor, but requires a specific
program or application that can understand its format.
To open binary files are similar to the text file open modes, except that they use the
“b” character to indicate binary mode.
42
Parameter Mode Description
rb Read Open a binary file for reading only; the file pointer is
placed at the beginning of the file.
rb+ Read/Write Open a binary file for both reading and writing; the file
pointer is placed at the beginning.
wb Write Open a binary file for writing only; overwrites the file if it
exists, creates a new file if it doesn't.
wb+ Write/Read Open a binary file for both writing and reading; overwrites
the file if it exists, creates a new file if it doesn't.
ab Append Open a binary file for appending; the file pointer is at the
end of the file if it exists; creates a new file if it doesn't.
ab+ Append/Read Open a binary file for both appending and reading; the file
pointer is at the end of the file if it exists; creates a new file
if it doesn't.
Pickle Module
The pickle module is a built-in module that provides functions for serializing and
deserializing python objects.
Serialization is the process of converting an object into a stream of bytes that can be
stored in a file or transmitted over network.
Deserialization is the reverse process of converting a stream of bytes back into an
object.
The pickle module can handle most python objects, such as lists, dictionaries, classes,
functions, ets. But not all.
The pickle module provides two methods to work with binary files for pickling and
unpickling, respectively:
The dump() method:
The dump() takes an object and a file object as arguments and writes the
serialized bytes of the object to the file.
The file in which data are to be dumped, needs to be opened in binary write mode
( wb ).
import pickle
pickle.dump(list_values, file_object)
file_object.close()
43
The laod() method takes a file object as an argument and returns the
deserialized object from the bytes read from the file.
The file to be loaded is opened in binary read ( rb ) mode.
import pickle
object_var = pickle.load(file_object)
file_object.close()
print(object_var)
File Operations
Read
To read data from binary file, we can use methods like read() , readline() , or
readlines() .
However these methods will return bytes objects instead of strings. We can also use
struct.unpack() to convert bytes into other data types, such as integers, floats, etc.
f = open("numbers.bin", "rb")
data = f.read(4)
f.close()
print(number)
Write or Create
To write or create data in a binary file, we can use methods like write() or
writelines , just like in text files.
However, these methods will take bytes objects instead of strings. We can also use
struct.pack() to convert other data types into bytes, such as integers, floats, etc.
44
import struct
f = open("number.bin", "wb")
f.close()
CSV File
A CSV file is a file that contains data in the form of characters separated by commas.
CSV files are often used to store and exchange data between different applications
that can handle tabular data, such as spreadsheets, databases, contact managers,
etc.
The CSV module is a built-in module that provides functions and classes for reading
and writing data in CSV format.
CSV stands for comma-separated values, which is a common format for storing and
exchanging tabular data, such as spreadsheets and databases.
import csv
f = open(“people.csv”,”r”,newline=””)
import csv
f = open(“people.csv”,”r”,newline=””)
f.close()
45
To write data into a CSV file in python, we use csv.writer() function to create a
writer object that data to the file.
The writer object has methods like writerow() and writerows() that can write one or
more rows of data to the file.
import csv
import csv
46
# Manually close the file
csvfile.close()
If your CSV file has a header row, you might want to use DictReader to read each row
as a dictionary
import csv
OS Modules
Python has a built-in OS module with methods for interacting with the operating
system, like creating files and directories, management of files and directories, input,
output, environment variables, process management, etc.
OS Path module contains some useful functions on pathnames. The path parameters
are either strings or bytes.
These functions here are used for different purposes such as for merging, normalizing,
and retrieving path names in Python.
All of these functions accept either only bytes or only string objects as their
parameters.
The result is an object of the same type if a path or file name is returned.
As there are different versions of the operating system there are several versions of
this module in the standard library
The os and os.path modules include many functions to interact with the file system
47
import os
cwd = os.getcwd()
print("Current Working Directory: ", cwd)
import os
def current_path():
print("Current Working Directory: ")
print(os.getcwd())
print()
current_path()
os.chdir('../')
current_path()
Creating a Directory
Using os.mkdir()
By using os.mkdir() method in Python is used to create a directory named path with
the specified numeric mode.
This method raises FileExistsError if the directory to be created already exists
import os
directory = "SOUNotes"
parent_dir = "D:/Projects/"
path = os.path.join(parent_dir, directory)
os.mkdir(path)
print("Directory '%s' created" %directory)
directory = "Notes"
parent_dir = "D:/Projects/"
mode = 0o666
48
Using os.makedirs()
import os
directory = "SOUNotes"
parent_dir = "D:/Projects/"
path = os.path.join(parent_dir, directory)
os.makedirs(path)
print("Directory '%s' created" %directory)
directory = "Notes"
parent_dir = "D:/Projects/"
mode = 0o666
import os
path = "/"
dir_list = os.listdir(path)
os.remove() method in Python is used to remove or delete a file path. This method
can not remove or delete a directory.
If the specified path is a directory then OSError will be raised by the method
import os
file = "demo.txt"
49
location = "D:/Projects/"
path = os.path.join(location, file)
os.remove(path)
Using os.rmdir()
import os
directory = "SOUNotes"
parent = "D:/Projects/"
path = os.path.join(parent, directory)
os.rmdir(path)
Questions
1. Explain file types detail in python.
2. Explain file handling function in python.
3. Write a function in python to read the content from a text file Demo.txt line by line
and display the same on screen.
4. Explain pickle Module with an example.
5. How can you join two path components using the os.path module? Provide an
example.
6. What is the purpose of the open() function in Python, and what are the common
modes you can use to open a file? List at least three modes.
7. Why is the Pickle module needed? Discuss the advantages and disadvantages of the
Pickle module.
8. Differentiate Python Binary file and Python Text file.
9. What is File? Write a Python program to read a CSV file, and write data into CSV file.
10. List out Python OS module functions. Explain current working directory with an
example
50
SOUNotes
SOUNotes
SOUNotes