0% found this document useful (0 votes)
12 views42 pages

Python File Handling and SQLite Basics

Uploaded by

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

Python File Handling and SQLite Basics

Uploaded by

bhumikaraju2006
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Unit III

Files: Types of files, Creating and Reading Text Data, File Methods to Read and
Write Data, Reading and Writing Binary Files,The Pickle module, Reading and
writing CSV files, Python SQLite: The SQLite3 module; - connect, cursor, execute,
close; Connect to Database; Create Table; Operations on Tables- Insert, Select,
Update. Delete and Drop Records. Exception Handling: Types of Errors; Exceptions;
Exception Handling using try, except and finally.
.

Types of Files
File:A file is a named location on disk to store related information .In files we can store the data
permanently.
In Python, files are mainly of two types:
[Link] files and [Link] Files

Text Files
 Store data in human-readable form (characters).
 Data is stored as lines of text (each line ends with a newline \n).
 Each character is stored using encoding (like ASCII or UTF-8).
 File mode for text: "r" (read), "w" (write), "a" (append), r+(read or write mode),w+(write
and read mode),a+(append or read mode).
 Easy to create, read, and edit compared to binary files.
 Best when the focus is on readability rather than efficiency.

Common example of Text Files


Tabular Data:.csv,.tsv,etc
Document:.txt,.tex etc
web standards:.html,.xml,.css etc
Source code:.[Link] etc
Types of Files

Binary Files
 Store data in binary (0s and 1s) format, not human-readable.
 Data is stored as a sequence of bytes.
 Cannot be opened and understood directly in a text editor.
 Used for images, videos, audio, executables, and other media files.
 File mode for binary: "rb" (read binary), "wb" (write binary), "ab" (append binary),rb+(read
and write only mode in binary format),ab+(append and read read only mode).
 More efficient for storage and processing compared to text files.
 Data must be read/written using special functions (e.g., pickle, struct, or byte handling).
 Best when focus is on accuracy and speed rather than readability.

Common examples of Binary Files:


Document files:.pdf,.doc,.xls etc
Image files:.png,.jpg,.gif etc
Video files:.mp4,.avi etc
Archive files:.[Link] etc
Comparison: Text Files vs Binary Files

S.N Text Files Binary Files


o
1 Store data in human-readable form Store data in binary (0s and
(characters). 1s), not human-readable.
2 Stored as lines of text. Stored as sequence of bytes.
3 Examples: .txt, .csv, .py, .html Examples: .jpg, .png, .mp3,
.exe, .dat
4 Can be opened in text editors like Cannot be understood in text
Notepad. editors.
5 Used for simple data such as names, Used for images, videos,
numbers, or code. audio, executables.
6 File modes: r, w, a, rt, wt File modes: rb, wb, ab
7 Focus on readability. Focus on accuracy and
efficiency.
File Handling Operations

There are several file handling operation in [Link] basic four operations are:
[Link]:Open a file for reading and writing by using the open() function
[Link]:Once a file is open,we can read the contents of a file by using read()
method of the file object
[Link]:Write data to a file by using the write() method of the file object.
[Link]:Close a file by using the close() method of the file object
File Methods to Read and Write Data

•read(size) → Reads given number of characters (or whole file


if size not given).
•readline() → Reads one line.
•readlines() → Reads all lines into a list.
•write(string) → Writes string to file.
•writelines(list) → Writes list of strings to file.
•close() → Closes the file.
Creating and Reading Text Data

 Opening a File
file = open("[Link]", "w") # open in write mode
[Link]("Hello Students!") # write data
[Link]()

 Reading a File
file = open("[Link]", "r") # open in read mode
content = [Link]()
print(content)
[Link]()
Reading and Writing Binary Files

Writing Binary Data


with open("[Link]", "wb") as file:
data = b"Hello in binary"
[Link](data)
Reading Binary Data
with open("[Link]", "rb") as file:
data = [Link]()
print(data)
Pickle module

The pickle module is used for serializing and deserializing Python objects.
•Serialization (Pickling): Converting Python objects into byte streams.
•Deserialization (Unpickling): Converting byte streams back into Python objects.
•Stores objects in binary format.
•Commonly used file extension: .pkl.
•Supports many Python objects such as lists, dictionaries, tuples, sets, and even user-defined classes.

Provides two main function sets:


•dump() / dumps() → For pickling (saving objects).
•load() / loads() → For unpickling (loading objects).
•Pickled data is not human-readable.
•Used when we want to store Python objects permanently or send them across a network.
•Pickled objects can only be loaded back in Python (not compatible with other languages).
The pickle Module
 Pickle is used to store Python objects (lists, dicts, etc.) in a binary file and retrieve them.
 Writing Object using Pickle
import pickle
data = {"name": "Alice", "age": 21}
with open("[Link]", "wb") as file:
[Link](data, file)
 Reading Object using Pickle
import pickle
with open("[Link]", "rb") as file:
obj = [Link](file)
print(obj)
Pickling vs Unpickling in Python

Aspect Pickling Unpickling


Converting a Python object into
Converting a byte stream back
Definition a byte stream (for storage or
into a Python object.
transfer).
Save Python objects
Restore previously saved Python
Purpose permanently (in a file or
objects.
memory).
Usually stored with .pkl Reads from .pkl or any pickled
File Extension
extension. data.
- [Link](obj, file) → Save - [Link](file) → Load
object to file object from file
Main Methods
- [Link](obj) → Convert - [Link](bytes) → Convert
object to bytes bytes back to object
CSV (Comma Separated Values)
•CSV stands for Comma Separated Values.
•Stores tabular data (rows and columns) in plain text.
•Each line in a CSV file is a record/row.
•Values in a row are separated by a comma ( , )
•File Extension .csv
•Easy to import and export data between applications.
•Python provides a built-in csv module to handle CSV files.
•Usually stores numeric and string data.
•Easy to share across platforms because of simple structure.
Two main Operation:
[Link]()-reads csv row by row
[Link]()-writes rows to csv file
Example data:
ID, Name, Marks
1, Alice, 85
2, Bob, 90
3, Charlie, 78
Writing CSV Files
Using [Link]()
•Writes rows to a CSV file as lists
import csv
with open("[Link]", "w", newline="") as file:
writer = [Link](file)
[Link](["Name", "Age"])
[Link](["Alice", 21])
[Link](["Bob", 22])
Reading from CSV
Using [Link]()
•Reads the file row by row as a list.
•Each row is returned as a list of strings.

import csv
with open("[Link]", "r") as file:
reader = [Link](file)
for row in reader:
print(row)
Random Access in Files (seek() and
tell())
What is Random Access?
•Normally, files are read sequentially (from beginning to end).
•Random access allows you to move the file pointer to
any position in the file and read/write from there.
•In Python, this is done using seek() and tell() methods.
1. seek(offset, from_what)
•Moves the file pointer to a specific location.
•offset → Number of bytes to move.
•from_what → Reference point:
•0 → beginning of file (default).
•1 → current position.
•2 → end of file.
Example:
f = open("[Link]", "rb")
[Link](5) # Move pointer to 5th byte
print([Link]()) # Prints: 5

2. tell()
•Returns the current position of the file pointer.
Example:
f = open("[Link]", "rb")
print([Link]()) # Prints: 0 (beginning)
[Link](10)
print([Link]()) # Prints: 10
[Link]()
pickle module
The pickle module is used to save Python objects into a file (serialization) and load
them back (deserialization).

Pickling → Converting a Python object into a byte stream (so it can be saved).
Unpickling → Converting the byte stream back into the original Python object.

Important Functions:
dumps() → Serializes (pickles) an object into a byte stream.
loads() → De-serializes (unpickles) a byte stream back into an object.
Example
import pickle
# A sample Python object
student = {"name": "John", "age": 20, "marks": [85, 90, 88]}
# Pickling: convert object into byte stream
byte_data = [Link](student)
print("Pickled Data (byte stream):")
print(byte_data)
# Unpickling: convert back to object
original_data = [Link](byte_data)
print("\nUnpickled Data (Python object):")
print(original_data)
Output:
Pickled Data (byte stream):
b'\x80\x04\x95...\x94.'
Unpickled Data (Python object):
{'name': 'John', 'age': 20, 'marks': [85, 90, 88]}
Python SQLite
Using sqlite3 Module in Python
The sqlite3 Module in python

 The SQLite3 module is a built-in Python library that allows interaction with
SQLite databases.
 No separate server required
 Useful for small projects and learning SQL
 Since Python comes with the SQLite3 module by default, you don’t need to
install it separately.
Features of SQLite
 Serverless: No need for a separate server process.
 Self-Contained: Entire database stored in a single file.
 Zero-Configuration: No installation or setup required.
 Transactional: Supports ACID transactions (Atomic,
Consistent, Isolated, Durable).
 Single-Database: All data stored in one cross-platform
database file.
SQLite Methods

 connect(): Connect to a database file


 cursor(): Create a cursor object to run SQL
 execute(): Run SQL queries like CREATE, INSERT, SELECT
 close(): Close the database connection
connect()

 To interact with an SQLite database, we first need to establish a connection


to it using the connect() method.
sqliteConnection = [Link]('database_name.db')
 If the specified database file doesn't exist, SQLite will create it automatically.
 After establishing the connection, we need to create a cursor object to
execute SQL queries on the database.
cursor()

 A Cursor is an object used to execute SQL queries on an SQLite database.


 It helps you run SQL queries (like creating tables, adding data, or getting
data) in an SQLite database.
 It acts as a middleware between the SQLite database connection and the SQL
commands.
 It is created after establishing a connection to the SQLite database.
import sqlite3
conn = [Link]('[Link]')
cur = [Link]() # cursor
Important Methods of cursor
Method Description

execute(sql_query) Executes a single SQL query

Executes SQL query against all parameter


executemany(sql_query, seq_of_parameters)
sequences

fetchone() Fetches the next row of a query result set

Fetches all (remaining) rows of a query result


fetchall()
set

fetchmany(size) Fetches the next set of rows of a result set

close() Closes the cursor


execute()

 In order to execute an SQLite script in python, we will use the execute()


method with connect() object:
[Link]("sql statement")
To perform the execution, we have to follow the below steps:
Import sqlite3 module
Example: import sqlite3
Create a connection to the database
Example: conn = [Link]('database_name.db')
Execute query using connection object
Example: [Link]('sql statement')
Finally, terminate the connection using the close() method
close()

 close() function is used to close the database connection in python.


 This function is useful for resource management and also to handle files and
memory for the connection database
 Closing the connection ensures that all transactions are properly saved and no
data corruption happens.
Syntax:
[Link]()
Operations on Tables- Insert, Select,
Update. Delete and Drop Records
Create Table
We c reate tables in the SQLite database from the Python program using the sqlite3 module.
Syntax
CREATE TABLE table_name (

column1 datatype PRIMARY KEY,


column2 datatype,
column3 datatype,
...
columnN datatype

);
 table_name: name of the table you want to create.
 column1, column2, ..., columnN: columns you want to include in your table.
 datatype: type of data that will be stored in each column (e.g., INTEGER, TEXT, REAL, etc.).
 PRIMARY KEY: column (or set of columns) that uniquely identifies each row in the table.
Steps to Create a Table in SQLite using
Python
 Import the SQLite3 Module: Use import sqlite3 to access SQLite functionality
in Python.
 Establish Connection: Use the connect() method to establish a connection to
your SQLite database.
 Create a Cursor Object: The cursor() method creates a cursor object that
allows you to execute SQL commands.
 Execute SQL Query: The execute() method of the cursor object is used to run
the SQL CREATE TABLE command.
 Close the Connection: After executing the required commands, it is essential
to close the connection to the database.
Insert Records

 The INSERT INTO statement is used to insert new rows into a table.
 There are two main methods for inserting data:
[Link] values: Inserting data by specifying the values without column names.
In this approach, we insert data by specifying the values for all columns without mentioning column names.
Syntax:INSERT INTO table_name VALUES (value1, value2, value3,...);
Example:[Link]("INSERT INTO STUDENT VALUES ('Raju', '7th', 'A')")
[Link] names and values: Specifying both column names and their corresponding values for insertion.
Syntax:INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2, value3, ...);
 Example:[Link]("INSERT INTO STUDENT (CLASS, SECTION, NAME) VALUES ('7th', 'A', 'Raju')")
Select Records

 SELECT statement in SQLite is used to query and retrieve data from one or
more tables in a database. It allows you to choose which columns you want to
see, filter rows, sort results, and even perform calculations.
Example: SELECT * FROM student
*: Retrieves all columns from the table.
 If you want to select specific columns, replace * with the column names, e.g.,
SELECT column1, column2 FROM table_name.
Update Records

 The UPDATE statement in SQL is used to update the data of an existing table in the
database.
 We can update single columns as well as multiple columns using UPDATE statement
as per our requirement.
Syntax:
UPDATE table_name SET column1 = value1, column2 = value2,...
WHERE condition;
Example:
UPDATE student SET marks = 90 WHERE name = 'John'
 Use [Link]() after update
Delete Records

 Deleting data in SQLite is achieved using the DELETE statement, which can
optionally be combined with a WHERE clause to specify which rows to delete.
 Syntax:DELETE FROM table_name [WHERE Clause]
table_name: The name of the table from which you want to delete data.
WHERE condition: This is optional. It specifies the condition for which rows
to delete
 Example: DELETE FROM student WHERE name = 'John'
 Use [Link]() after delete
Drop Table

 DROP is used to delete the entire database or a table. It deleted both records
in the table along with the table structure.
 Syntax: DROP TABLE TABLE_NAME;
 Example: DROP TABLE student
 Removes entire table
Exception Handling

 Python Exception Handling handles errors that occur during the execution of a
program.
 Exception handling allows to respond to the error, instead of crashing the
running program
 It enables you to catch and manage errors, making your code more robust and
user-friendly
Difference Between Exception and Error

 Error: Errors are serious issues that a program should not try to handle. They
are usually problems in the code's logic or configuration and need to be fixed
by the programmer. Examples include syntax errors and memory errors.
 Exception: Exceptions are less severe than errors and can be handled by the
program. They occur due to situations like invalid input, missing files or
network issues.
Types of Errors

Types of Errors in Python


1. Syntax Error → Mistakes in code structure.
Example:
print("Hello" # Missing closing bracket
2. Runtime Error → Errors that happen while running the program.
Example:
x = 10 / 0 # Division by zero
3. Logical Error → The program runs but gives the wrong output.
# Find average but wrong formula used
avg = (10 + 20 + 30) / 2 # Incorrect
Exceptions

 Exception handling in Python deals with errors that occur while a program is
running.

 Instead of the program crashing, it allows us to catch and handle the error.

 This makes the code safe, user-friendly, and robust.


try, except and finally

 Exception handling in Python is done using the try, except and finally blocks.
 try:
 # Code that might raise an exception
 except SomeException:
 # Code to handle the exception
 finally:
 # Code to run regardless of whether an exception occurs
try, except and finally

 try Block: try block lets us test a block of code for errors. Python will "try" to
execute the code in this block. If an exception occurs, execution will immediately
jump to the except block.
 except Block: except block enables us to handle the error or exception. If the
code inside the try block throws an error, Python jumps to the except block and
executes it.
 finally Block: finally block always runs, regardless of whether an exception
occurred or not. It is typically used for cleanup operations (closing files, releasing
resources).
Example
try:
num = int(input("Enter a number: ")) # Asking user for input
result = 10 / num
print("Result:", result)
except ZeroDivisionError:
print("Error: You cannot divide by zero!")
except ValueError:
print("Error: Please enter a valid number.")
finally:
print("Program ended.")
Example Run:
Output:
Input: 5 → Output: Result: 2.0
Input: 0 → Output: Error: You cannot divide by zero!

You might also like