Unit :4
Files in Python: Types, Creating, and
Reading Text Data
What is a File?
A file is a collection of data stored on a disk with a specific name and path. In Python, we can
handle files using file handling operations, such as reading, writing, and appending.
Types of Files
Python mainly deals with two types of files:
1. Text Files (.txt, .csv, .json, etc.)
o Stores plain text data that is human-readable.
o Can be opened and edited using text editors like Notepad.
2. Binary Files (.jpg, .png, .mp3, .exe, etc.)
o Stores data in binary format (0s and 1s).
o Cannot be read directly in a text editor.
File Handling in Python
Python provides built-in functions to work with files:
open(): Opens a file.
read(): Reads content from a file.
write(): Writes content to a file.
close(): Closes the file.
Syntax of open()
file = open("[Link]", mode)
Here,
"[Link]" → Name of the file.
mode → Specifies the operation:
o "r" → Read mode (default).
o "w" → Write mode (creates a new file if not exists).
o "a" → Append mode (adds content at the end).
o "x" → Create mode (fails if file exists).
o "rb", "wb" → Read/Write in binary mode.
Creating and Writing to a Text File
File Methods to Write Data in Python
Python provides several file handling methods to perform write operations efficiently. Let's
explore these methods with examples.
File Methods for Writing Data
1. write() – Writes a string to the file.
2. writelines() – Writes multiple lines to the file from a list.
Example: Writing Data to a File
# Open file in write mode
file = open("[Link]", "w")
# Write single line
[Link]("Hello, this is a Python file handling example.\n")
# Write multiple lines using writelines()
lines = ["Python makes file handling easy.\n", "We can write multiple lines at once.\n"]
[Link](lines)
# Close the file
[Link]()
print("Data written successfully!")
✔ Creates [Link] (or overwrites if it exists).
✔ Writes one line using write().
✔ Writes multiple lines using writelines().
Example: Writing Text to a File
# Open a file in write mode
file = open("[Link]", "w")
# Write data to the file
[Link]("Hello, this is a text file in Python.\n" )
[Link]("Python makes file handling easy!")
# Close the file
[Link]()
print("File written successfully!")
✔ Creates (or overwrites) [Link].
✔ Writes two lines into the file.
In Python, when you open a file in write mode ("w") or append mode ("a"), the file will be
created automatically if it does not exist.
Behavior of Different Modes:
1. Write mode ("w")
o If the file does not exist, it is created.
o If the file already exists, it is overwritten (erasing existing content).
2. Append mode ("a")
o If the file does not exist, it is created.
o If the file already exists, new content is appended to the existing content.
3. Read mode ("r")
o The file must exist; otherwise, it will raise a FileNotFoundError.
Reading from a Text File
File Methods to Read Data in Python
Python provides several file handling methods to perform read operations efficiently. Let's
explore these methods with examples.
File Methods for Reading Data
1. read(size) – Reads the entire file or specified number of bytes.
2. readline() – Reads one line at a time.
3. readlines() – Reads all lines and returns a list.
Example: Reading an Entire File
# Open file in read mode
file = open("[Link]", "r")
# Read the entire content of the file
content = [Link]()
print("File Content:\n", content)
# Close the file
[Link]()
✔ Reads the entire file.
Reading a File Line by Line
Example: Using readline() and readlines()
python
file = open("[Link]", "r")
# Read first line
line1 = [Link]()
print("First Line:", line1)
# Read all lines into a list
lines = [Link]()
print("Remaining Lines:", lines)
[Link]()
✔ readline() → Reads one line at a time.
✔ readlines() → Reads all lines as a list.
Appending Data to a File
Example: Adding New Content
python
file = open("[Link]", "a") # Open in append mode
[Link]("\nThis is a new line added.")
[Link]()
# Verify by reading again
file = open("[Link]", "r")
print([Link]())
[Link]()
✔ Opens [Link] in append mode ("a").
✔ Adds new content at the end without overwriting existing data.
🔹 Using with Statement (Best Practice)
The with statement automatically closes the file after use.
with open("[Link]", "r") as file:
content = [Link]()
print(content) # File automatically closes after this block
✔ No need to call close().
✔ Prevents resource leakage.
Checking if a File Exists Before Opening
The import os statement in Python imports the os module, which provides functions to
interact with the operating system, such as file handling, directory management, and
environment variables.
[Link]("[Link]")
[Link]("[Link]") checks whether the file [Link] exists in the current
directory.
It returns True if the file exists and False if it does not.
Why Use [Link]()?
Prevents errors when trying to read or delete a non-existent file.
Useful in conditional file operations like checking before opening or deleting a file.
Example Usage
import os
if [Link]("[Link]"):
with open("[Link]", "r") as file:
print([Link]())
else:
print("File does not exist!")
✔ Prevents FileNotFoundError if the file does not exist.
Summary
✅ Text files store human-readable data.
✅ open() is used to handle files.
✅ Modes determine file operations ("r", "w", "a", etc.).
✅ Use with open() to handle files safely.
Reading and Writing Binary Files in Python
Binary files store data in binary format (0s and 1s) instead of plain text. These files include
images, audio, videos, and executable files. Python provides file handling methods for
working with binary files.
1. What is a Binary File?
A binary file is a file that stores data in binary format (0s and 1s), rather than plain text.
Unlike text files, binary files can store any type of data, including images, audio, video,
executables, and compiled programs.
2. Why Do We Need Binary Files?
Efficient Storage: Binary files take up less space compared to text files because data is stored in a
compressed and machine-readable format.
Faster Processing: They are faster to read and write because there is no need to convert data
between human-readable and machine-readable formats.
Data Integrity: Binary files preserve exact data, unlike text files, which may undergo changes (e.g.,
newline conversions).
Handling Complex Data: Suitable for storing complex structures like images, audio, or serialized
objects.
Example: Writing Binary Data
# Open a file in binary write mode
with open("binary_file.bin", "wb") as file:
data = bytearray([65, 66, 67, 68, 69]) # ASCII values of A, B, C, D, E
[Link](data)
print("Binary file written successfully.")
✔ Creates binary_file.bin.
✔ Writes binary data (bytearray) to the file.
Reading from a Binary File
To read a binary file, open it in binary read mode ("rb").
Example: Reading Binary Data
# Open file in binary read mode
with open("binary_file.bin", "rb") as file:
data = [Link]() # Read entire file content
print("Binary Data:", data)
# Convert binary to list of integers
int_data = list(data)
print("Converted Data:", int_data)
✔ Reads binary data.
✔ Converts bytes into integer list ([65, 66, 67, 68, 69]).
3. Difference Between Binary File and Text
File
Feature Text File (.txt) Binary File (.bin)
Storage Format Human-readable text Machine-readable binary (0s and 1s)
Encoding Uses character encoding (UTF-8, ASCII) Stores raw data (no encoding)
File Operations Readable with a text editor Requires specialized software
Use Cases Storing simple text, logs, configs Storing images, videos, executables
Size Generally larger Smaller (compressed format)
Processing Speed Slower due to encoding conversion Faster, as it reads raw data
4. Example: Working with Text and Binary
Files in Python
Text File Operations
# Writing to a text file
with open("[Link]", "w") as file:
[Link]("Hello, this is a text file.\n")
[Link]("Python makes file handling easy.")
# Reading from a text file
with open("[Link]", "r") as file:
content = [Link]()
print("Text File Content:\n", content)
# Appending to a text file
with open("[Link]", "a") as file:
[Link]("\nAppending new text to the file.")
Binary File Operations
python
# Writing binary data to a file
data = b'\x48\x65\x6C\x6C\x6F' # "Hello" in binary
with open("[Link]", "wb") as file:
[Link](data)
# Reading binary data from a file
with open("[Link]", "rb") as file:
binary_content = [Link]()
print("Binary File Content:", binary_content)
Key Takeaways
Use text files for storing readable content (e.g., documents, logs).
Use binary files for storing non-text data (e.g., images, audio, video).
Reading and writing binary files is done using "rb" and "wb" modes
The pickle Module in Python
The pickle module allows you to serialize (convert objects into a byte stream) and
deserialize (convert byte stream back to objects) Python objects.
It is mainly used to save and load Python objects such as lists, dictionaries, tuples, and even
custom objects for later use.
Why Do We Need pickle ?
1. ✅ Save Python objects to files (e.g., store machine learning models, game data, configurations).
2. ✅ Send objects over a network (useful in client-server applications).
3. ✅ Reduce computation time (store precomputed results instead of recalculating).
4. ✅ Share complex Python objects between programs.
How to Use pickle ?
1️Pickling (Saving an Object to a File)
import pickle
# Python object (dictionary)
data = {"name": "Alice", "age": 25, "city": "New York"}
# Open file in binary write mode
with open("[Link]", "wb") as file:
[Link](data, file) # Serialize and save to file
print("Data saved successfully!")
✔ wb → Write in binary mode
✔ [Link](obj, file) → Converts object into bytes and saves it
2️⃣ Unpickling (Loading the Object Back)
import pickle
# Open file in binary read mode
with open("[Link]", "rb") as file:
loaded_data = [Link](file) # Deserialize and load from file
print("Loaded Data:", loaded_data)
✔ rb → Read in binary mode
✔ [Link](file) → Loads the object back from the file
🔹 Output:
Loaded Data: {'name': 'Alice', 'age': 25, 'city': 'New York'}
Pickling & Unpickling Custom Objects
You can also pickle custom Python classes! 🚀
Pickling a Custom Class
import pickle
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
def __repr__(self):
return f"Person(name={[Link]}, age={[Link]})"
person = Person("Bob", 30)
# Save object to file
with open("[Link]", "wb") as file:
[Link](person, file)
print("Person object saved!")
Unpickling the Custom Class
Reading and Writing CSV Files in Python
CSV (Comma-Separated Values) files are used to store tabular data in plain text format. Each
row in a CSV file represents a data record, and each column is separated by a comma (,) or
another delimiter.
Example CSV Content:
Name,Age,City
Alice,25,New York
Bob,30,Los Angeles
Charlie,28,Chicago
Why Do We Need CSV Files?
1. Lightweight and Simple Format
CSV files store data in plain text, making them easy to create and read.
They do not require complex software or databases to access.
2. Platform and Software Independence
CSV files can be opened in Excel, Google Sheets, Notepad, Python, R, and databases like MySQL.
No specific software is required to work with CSV files.
then Not to Use CSV Files?
🚫 Limitations of CSV Files:
Not suitable for complex data structures (e.g., nested data, images, or large relational databases).
No support for data types (e.g., all data is stored as text).
Cannot handle concurrent modifications well.
Writing to a CSV File
To write data into a CSV file, we use [Link]().
Example: Writing to a CSV File
import csv
# Data to be written to CSV
data = [
["Name", "Age", "City"],
["Alice", 25, "New York"],
["Bob", 30, "Los Angeles"],
["Charlie", 28, "Chicago"]
# Open a CSV file in write mode
with open("[Link]", "w", newline="") as file:
writer = [Link](file) # Create a CSV writer object
[Link](data) # Write multiple rows
print("CSV file has been written successfully.")
Explanation
"w" mode is used to create and write to the file.
newline="" prevents extra blank lines in Windows.
[Link](file) creates a CSV writer object.
[Link](data) writes multiple rows at once.
Reading from a CSV File
To read data from a CSV file, we use [Link]().
Example: Reading from a CSV File
import csv
# Open the CSV file in read mode
with open("[Link]", "r") as file:
reader = [Link](file) # Create a CSV reader object
for row in reader:
print(row) # Print each row as a list
Explanation
"r" mode is used to read the file.
[Link](file) creates a CSV reader object.
We iterate through the reader object to print each row.
Output:
['Name', 'Age', 'City']
['Alice', '25', 'New York']
['Bob', '30', 'Los Angeles']
['Charlie', '28', 'Chicago']
1. What is a DataFrame?
A DataFrame is a table-like data structure in Pandas, similar to an Excel sheet. It helps in
organizing and analyzing data efficiently.
📌 Example Excel File ([Link]):
Ag Salar Departm
Name
e y ent
5000
Alice 25 HR
0
6000
Bob 30 IT
0
Charli 5500
28 Finance
e 0
2. Installing Required Libraries
Before we start, install the required Python libraries:
pip install pandas openpyxl matplotlib seaborn
pandas: To handle data.
openpyxl: To read Excel files.
matplotlib & seaborn: For visualization.
3. Reading an Excel File into a DataFrame
Let's read the [Link] file into a DataFrame:
import pandas as pd
# Load the Excel file into a DataFrame
df = pd.read_excel("[Link]", engine="openpyxl")
# Display the first 5 rows
print([Link]())
Output:
🔹 Expected Output (First 5 Rows):
Name Age Salary Department
0 Alice 25 50000 HR
1 Bob 30 60000 IT
2 Charlie 28 55000 Finance
df is the DataFrame.
pd.read_excel("[Link]", engine="openpyxl") reads data from the Excel file and
stores it in df (which is a Pandas DataFrame).
[Link]() displays the first 5 rows of the DataFrame.
Why Do We Need a DataFrame When We Can Store Data in
an Excel File?
Yes, we can store data in an Excel file, but using a DataFrame in Python (via Pandas)
provides many advantages over just storing data in Excel. Let's explore why DataFrames
are useful and how they improve data handling and analysis.
1. Excel Stores Data, But DataFrame Allows Efficient
Analysis
📌 Excel is mainly a storage tool, while a DataFrame is a powerful data manipulation
tool.
In Excel, you can store data in rows and columns and perform some built-in calculations (SUM,
AVERAGE, etc.).
With a DataFrame, you can apply complex operations (sorting, filtering, merging, statistical analysis)
quickly.
Creating a DataFrame from a CSV File in Pandas
What is a DataFrame?
A Pandas DataFrame is a 2 dimensional data structure, like a 2 dimensional array, or a table with
rows and columns.
Creating a DataFrame from a Dictionary
In Pandas, we can use a dictionary where the keys represent column names, and the values
are lists of column data.
Example: Creating a DataFrame from a Dictionary
import pandas as pd
# Creating a dictionary
data = {
"Name": ["Alice", "Bob", "Charlie"],
"Age": [25, 30, 28],
"Salary": [50000, 60000, 55000]
}
# Converting dictionary into DataFrame
df = [Link](data)
# Display DataFrame
print(df)
Output:
Name Age Salary
0 Alice 25 50000
1 Bob 30 60000
2 Charlie 28 55000
✅ Why Use a Dictionary?
Easy to create structured data.
Column names are automatically assigned from dictionary keys.
Flexible – Can add more columns dynamically.
CSV file
A CSV (Comma-Separated Values) file stores tabular data in plain text, where each line
represents a row, and values are separated by commas. Pandas makes it easy to read CSV
files and convert them into a DataFrame for data analysis.
Reading a CSV File into a DataFrame
Example: Load CSV into DataFrame
import pandas as pd
# Reading a CSV file into a DataFrame
df = pd.read_csv("[Link]")
# Display first 5 rows
print([Link]())
✅ Explanation:
pd.read_csv("[Link]") → Reads the CSV file and loads it into a DataFrame.
[Link]() → Displays the first 5 rows of the DataFrame.
Writing a DataFrame to a CSV File
If we have a DataFrame and want to save it as a CSV file, we can use to_csv().
Example: Write DataFrame to CSV
import pandas as pd
# Creating a sample DataFrame
data = {
"Name": ["Alice", "Bob", "Charlie"],
"Age": [25, 30, 28],
"Salary": [50000, 60000, 55000]
}
df = [Link](data)
# Writing DataFrame to a CSV file
df.to_csv("[Link]", index=False) # index=False to avoid writing row numbers
print("Data saved to [Link]")
Creating a DataFrame from Tuples
A DataFrame can also be created using a list of tuples, where each tuple represents a row.
Example: Creating a DataFrame from Tuples
import pandas as pd
# Creating a list of tuples
data = [
("Alice", 25, 50000),
("Bob", 30, 60000),
("Charlie", 28, 55000)
]
# Defining column names
columns = ["Name", "Age", "Salary"]
# Creating DataFrame from tuples
df = [Link](data, columns=columns)
# Display DataFrame
print(df)
Output:
Name Age Salary
0 Alice 25 50000
1 Bob 30 60000
2 Charlie 28 55000
✅ Why Use Tuples?
Each tuple represents a row – Easy to convert from database query results.
Column names must be manually defined (unlike dictionaries).
More readable when working with row-based data.
Operations on DataFrames in Pandas (with Examples)
1. Creating a DataFrame
You can create a DataFrame from a dictionary:
import pandas as pd
# Creating a DataFrame from a dictionary
data = {
"Name": ["Alice", "Bob", "Charlie", "David"],
"Age": [25, 30, 28, 35],
"City": ["New York", "Los Angeles", "San Francisco", "Chicago"]
}
df = [Link](data)
print(df)
✔️Output:
Name Age City
0 Alice 25 New York
1 Bob 30 Los Angeles
2 Charlie 28 San Francisco
3 David 35 Chicago
Basic Operations on DataFrames
[Link] Data
print([Link]()) # First 5 rows
print([Link]()) # Last 5 rows
print([Link]()) # Summary of DataFrame
print([Link]()) # Statistical summary of numerical columns
2. Selecting Specific Columns
print(df["Name"]) # Select a single column
print(df[["Name", "Age"]]) # Select multiple columns
✔️Output:
0 Alice
1 Bob
2 Charlie
3 David
Name: Name, dtype: object
3. Selecting Specific Rows (Using Indexing)
print([Link][1]) # Select row by index label
print([Link][2]) # Select row by index position
4. Filtering Data
print(df[df["Age"] > 28]) # Filter rows where Age > 28
✔️Output:
Name Age City
1 Bob 30 Los Angeles
3 David 35 Chicago
8. Deleting Columns and Rows
[Link]("Salary", axis=1, inplace=True) # Delete 'Salary' column
[Link](2, axis=0, inplace=True) # Delete row with index 2
print(df)
Sorting Data
print(df.sort_values(by="Age", ascending=False)) # Sort by Age
(Descending)
Grouping and Aggregation
print([Link]("City")["Age"].mean()) # Average age per city
Pandas DataFrames allow for powerful data analysis with operations like:
✅ Viewing & Selecting Data
✅ Filtering & Sorting
✅ Adding & Removing Columns
✅ Grouping & Aggregation
✅ Exporting Data
Data Visualization using Matplotlib: Bar Graph,
Histogram, Pie Chart, and Line Graph
Matplotlib is a powerful Python library for data visualization. Let's explore how to create
different types of graphs using Matplotlib.
Bar Graph
A bar graph is used to represent categorical data with rectangular bars.
Example: Creating a Bar Graph
import [Link] as plt
# Data
categories = ["A", "B", "C", "D"]
values = [10, 20, 15, 25]
# Create Bar Graph
[Link](categories, values, color='blue')
# Labels and Title
[Link]("Categories")
[Link]("Values")
[Link]("Bar Graph Example")
# Show Graph
[Link]()
Output
The x-axis represents categories (A, B, C, D).
The y-axis represents values (10, 20, 15, 25).
Each bar represents the respective category with its value.
Histogram
A histogram is used to represent the distribution of a dataset.
Example: Creating a Histogram
import numpy as np
# Random dataset
data = [Link](1000)
# Create Histogram
[Link](data, bins=30, color='green', edgecolor='black')
# Labels and Title
[Link]("Value Ranges")
[Link]("Frequency")
[Link]("Histogram Example")
# Show Graph
[Link]()
Output:
A histogram displaying the frequency distribution of random data.
Step-by-Step Breakdown:
[Link] numpy as np
This imports the NumPy library, which is used for numerical computations.
2. import [Link] as plt
This imports Matplotlib’s pyplot module, which is used for creating visualizations.
3. data = [Link](1000)
This generates 1000 random numbers from a normal (Gaussian) distribution with a mean of 0
and a standard deviation of 1.
The randn() function creates a NumPy array of random numbers that follow a standard
normal distribution.
4. [Link](data, bins=30, color='green', edgecolor='black')
[Link](data, bins=30):
Creates a histogram of the data.
The bins=30 argument divides the range of data into 30 bins (intervals).
color='green':
Sets the color of the bars in the histogram to green.
edgecolor='black':
Adds a black outline around each bar to improve visibility.
What the Histogram Represents?
A histogram is a type of bar graph that shows the frequency distribution of numerical data.
The x-axis represents the range of values (data points).
The y-axis represents the count (frequency) of occurrences of those values in the dataset.
Example Output:
This will generate a histogram where:
The x-axis has 30 bins, each representing a range of values.
The y-axis shows how many data points fall within each bin.
The bars are green with black edges.
Pie Chart
A pie chart represents categorical data in a circular format.
Example: Creating a Pie Chart
# Data
labels = ["Python", "Java", "C++", "JavaScript"]
sizes = [40, 30, 20, 10]
colors = ["gold", "lightblue", "lightcoral", "lightgreen"]
# Create Pie Chart
[Link](sizes, labels=labels, colors=colors, autopct="%1.1f%%",
startangle=140)
# Title
[Link]("Programming Language Popularity")
# Show Graph
[Link]()
✔ Output: A pie chart showing the popularity of different programming
languages.
Line Graph
A line graph is useful for showing trends over time.
Example: Creating a Line Graph
# Data
x = [1, 2, 3, 4, 5]
y = [10, 15, 7, 20, 18]
# Create Line Graph
[Link](x, y, marker="o", linestyle="--", color="red")
# Labels and Title
[Link]("Time (Days)")
[Link]("Value")
[Link]("Line Graph Example")
# Show Graph
[Link]()
What is a Database?
A database is an organized collection of data that can be easily accessed, managed, and
updated.
Types of Databases
1. Relational Databases (RDBMS) - Store data in tables with relationships (e.g., MySQL, PostgreSQL).
🔹 Examples:
✅ MySQL – Open-source, widely used for web applications.
✅ PostgreSQL – Advanced RDBMS with support for complex queries.
✅ Oracle DB – Used for enterprise applications.
✅ Microsoft SQL Server – Used in corporate environments.
2. NoSQL Databases
Definition: Stores data in flexible formats such as key-value pairs, documents, columns, or graphs.
Does not use SQL for queries (hence "NoSQL").
Designed for high scalability and handling unstructured data.
Types of NoSQL Databases:
✅ Document-based (e.g., MongoDB) – Stores data as JSON-like documents.
✅ Key-Value Store (e.g., Redis, DynamoDB) – Stores data in key-value pairs, fast retrieval.
✅ Column-Family Store (e.g., Cassandra, HBase) – Uses columns instead of rows for faster
analytics.
✅ Graph Database (e.g., Neo4j) – Stores and queries relationships between entities.
3. In-Memory Databases
Definition: Stores data in RAM (Random Access Memory) instead of a disk for ultra-fast access.
Provides lower latency compared to traditional disk-based databases.
Often used as a cache to speed up data retrieval.
🔹 Examples:
✅ Redis – Fast key-value store used for caching.
✅ Memcached – High-speed caching system.
What is MySQL?
MySQL is an open-source Relational Database Management System (RDBMS).
It follows the Structured Query Language (SQL).
Supports CRUD operations (Create, Read, Update, Delete).
INSTALLING MYSQL
Steps to Install MySQL
1. Download MySQL from MySQL Official Website
2. Install MySQL Server (Choose MySQL Community Server).
3. Set up a Root Password for authentication.
4. Install MySQL Workbench (Optional GUI for managing MySQL).
5. Verify Installation
o
Open Command Prompt (cmd) or Terminal and type:
mysql -u root –p
USING MYSQL FROM PYTHON
To connect Python with MySQL, you need to install the MySQL Connector.
1. Install MySQL Connector
Run the following command:
pip install mysql-connector-python
2. Connect Python to MySQL
import [Link]
# Establish connection
conn = [Link](
host="localhost",
user="root",
password="yourpassword",
database="testdb"
)
# Check connection
if conn.is_connected():
print("Connected to MySQL Database!")
[Link]()
3. PERFORMING CRUD OPERATIONS IN MYSQL USING PYTHON
1. Creating a Database and Table
import [Link]
conn = [Link](
host="localhost",
user="root",
password="yourpassword"
)
cursor = [Link]()
# Create Database
[Link]("CREATE DATABASE IF NOT EXISTS SchoolDB")
# Select the Database
[Link]("USE SchoolDB")
# Create Table
[Link]("""
CREATE TABLE IF NOT EXISTS Students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50),
age INT,
grade VARCHAR(10)
)
""")
print("Database and Table created successfully!")
[Link]()
What is a Cursor in MySQL (Python)?
A cursor in MySQL (when using Python) is an interface that allows us to execute SQL
queries and fetch data from the database.
🔹 Why Do We Need a Cursor?
Python doesn’t directly execute SQL queries.
A cursor acts as a middleman between Python and MySQL.
It sends SQL commands to the database and retrieves results.
How to Create a Cursor?
cursor = [Link]()
[Link]() creates a cursor object that allows us to run SQL commands.
conn is the database connection.
Is It Possible to Run Queries Without a Cursor?
🚫 No, it is not possible to execute SQL queries in Python without a cursor.
Why?
The cursor acts as a communication link between Python and MySQL.
If you don't create a cursor, Python has no way to send SQL commands to the database.
The database requires a structured way to process queries, and the cursor provides this structure.
Closing the Cursor
After using the cursor, always close it to free up resources.
[Link]()
[Link]()
Why Use Triple Quotes (""" """) in SQL Queries?
The triple quotes (""" """) in Python allow multi-line strings, making it easier to write
complex SQL queries that span multiple lines.
🔹 Why Not Use Single or Double Quotes?
You can use single (') or double (") quotes, but for long queries, it becomes difficult to
manage.
✅ Using Triple Quotes (Recommended for Readability)
Final Summary
Feature Purpose
cursor = [Link]() Creates a cursor object to execute SQL queries
[Link]("SQL COMMAND") Runs an SQL command
[Link]() Fetches multiple rows from the database
[Link]() Fetches a single row
[Link]() Saves changes (for INSERT, UPDATE, DELETE)
[Link]() Closes the cursor
2 INSERTING DATA INTO A TABLE
import [Link]
conn = [Link](
host="localhost",
user="root",
password="yourpassword",
database="SchoolDB"
)
cursor = [Link]()
# Insert Data
query = "INSERT INTO Students (name, age, grade) VALUES (%s, %s, %s)"
values = ("Alice", 20, "A")
[Link](query, values)
[Link]()
print("Record Inserted Successfully!")
[Link]()
3. RETRIEVING DATA FROM A TABLE
import [Link]
conn = [Link](
host="localhost",
user="root",
password="yourpassword",
database="SchoolDB"
)
cursor = [Link]()
# Fetch all rows
[Link]("SELECT * FROM Students")
rows = [Link]()
for row in rows:
print(row) # Print each row
[Link]()
2 UPDATING RECORDS IN A TABLE
import [Link]
conn = [Link](
host="localhost",
user="root",
password="yourpassword",
database="SchoolDB"
)
cursor = [Link]()
# Update a record
query = "UPDATE Students SET age = %s WHERE name = %s"
values = (22, "Alice")
[Link](query, values)
[Link]()
print("Record Updated Successfully!")
[Link]()
4. DELETING RECORDS FROM A TABLE
import [Link]
conn = [Link](
host="localhost",
user="root",
password="yourpassword",
database="SchoolDB"
)
cursor = [Link]()
# Delete a record
query = "DELETE FROM Students WHERE name = %s"
values = ("Alice",)
[Link](query, values)
[Link]()
print("Record Deleted Successfully!")
[Link]()