Files in Python
🌟 1. What is a File?
A file is a place on your computer where data is stored permanently.
When we close a program, the data stored in variables or memory disappears.
To save data for future use, we store it in a file.
For example:
A text file ([Link]) can store names or sentences.
A binary file ([Link]) can store pictures or videos.
A CSV file stores data in a table format like Excel.
In Python, we can create, open, read, write, and close files easily using file handling
functions.
⚙️2. Types of Files
There are mainly two types of files in Python:
Readable by
Type Extension Description
Humans?
Text Stores data as plain
.txt, .csv, .json ✅ Yes
File text characters.
Binary Stores data in binary
.bin, .dat, .pkl, .jpg ❌ No
File form (0s and 1s).
📘 3. Working with Text Files
🔹 (a) Opening a File
In Python, we use the open() function to open a file.
Syntax:
file_object = open("filename", "mode")
Common Modes:
Mode Meaning Description
"r" Read Opens file for reading (default mode)
Opens file for writing (overwrites
"w" Write
existing data)
"a" Append Opens file to add data at the end
Read and
"r+" Opens file for both reading and writing
Write
Write and
"w+" Overwrites and then allows reading
Read
Append and
"a+" Appends and allows reading
Read
"rb", "wb", Binary
Used for binary files
"ab" Modes
🔹 (b) Creating and Writing to a Text File
To create and write to a text file:
f = open("[Link]", "w")
[Link]("Hello, this is my first file in Python.\n")
[Link]("File handling is easy!")
[Link]()
This code will create a file named [Link] and write two lines in it.
If the file already exists, it will be overwritten.
🔹 (c) Reading from a Text File
To read data from the file:
f = open("[Link]", "r")
content = [Link]() # reads entire file
print(content)
[Link]()
Output:
Hello, this is my first file in Python.
File handling is easy!
You can also read line by line:
f = open("[Link]", "r")
for line in f:
print(line)
[Link]()
or read only one line:
f = open("[Link]", "r")
line = [Link]()
print(line)
[Link]()
🔹 (d) Appending to a Text File
Appending means adding new data at the end of the file without removing old data.
f = open("[Link]", "a")
[Link]("\nThis line is added later.")
[Link]()
Now your file will contain both the old and new text.
🔹 (e) Closing the File
Always close the file after reading or writing using:
[Link]()
This releases memory and saves all data properly.
🔹 (f) Using with Statement
A better and safer way to handle files is using with:
with open("[Link]", "r") as f:
data = [Link]()
print(data)
The file automatically closes after use.
💾 4. Working with Binary Files
Binary files store data as a series of bytes (0s and 1s).
They are used to store non-text data like images, audio, video, or even Python
objects.
Example:
# Writing binary data
f = open("[Link]", "wb")
[Link](b"Python Binary File Example") # 'b' means bytes
[Link]()
# Reading binary data
f = open("[Link]", "rb")
data = [Link]()
print(data)
[Link]()
Output:
b'Python Binary File Example'
Binary files cannot be read directly by humans — they are machine-readable.
🥒 5. The Pickle Module
Sometimes we want to store Python objects (like lists, dictionaries, etc.) directly into
a file.
The pickle module allows us to convert Python objects into binary format (called
pickling) and save them.
We can also retrieve them back later (called unpickling).
➕ Example: Writing (Pickling)
import pickle
student = {"name": "Nav", "age": 21, "marks": 88}
# Write object to binary file
with open("[Link]", "wb") as f:
[Link](student, f)
📖 Example: Reading (Unpickling)
import pickle
# Read object from file
with open("[Link]", "rb") as f:
data = [Link](f)
print(data)
Output:
{'name': 'Nav', 'age': 21, 'marks': 88}
This is very useful for saving complex Python data structures permanently.
📊 6. Reading and Writing CSV Files
🔸 What is a CSV File?
CSV stands for Comma Separated Values.
It stores tabular data (like Excel) in plain text format — each row is a record, and
each column is separated by commas.
Example:
Name,Age,City
Nav,20,Delhi
Ravi,22,Mumbai
🔸 Writing Data to CSV File
We use the csv module to write data.
import csv
with open("[Link]", "w", newline="") as f:
writer = [Link](f)
[Link](["Name", "Age", "City"]) # header
[Link](["Nav", 20, "Delhi"])
[Link](["Ravi", 22, "Mumbai"])
🔸 Reading Data from CSV File
import csv
with open("[Link]", "r") as f:
reader = [Link](f)
for row in reader:
print(row)
Output:
['Name', 'Age', 'City']
['Nav', '20', 'Delhi']
['Ravi', '22', 'Mumbai']
🔸 Using Dictionary Format (Optional)
You can also read/write CSV data as dictionaries.
import csv
# Writing as dictionary
with open("[Link]", "w", newline="") as f:
fieldnames = ["Name", "Age", "City"]
writer = [Link](f, fieldnames=fieldnames)
[Link]()
[Link]({"Name": "Nav", "Age": 20, "City": "Delhi"})
[Link]({"Name": "Ravi", "Age": 22, "City": "Mumbai"})
🌐 7. Reading and Writing JSON Files
🔸 What is JSON?
JSON (JavaScript Object Notation) is a popular data format used for data exchange
between computers or web servers.
It looks like a Python dictionary.
Example JSON:
{
"name": "Nav",
"age": 20,
"city": "Delhi"
}
🔸 Writing to a JSON File
import json
data = {"name": "Nav", "age": 20, "city": "Delhi"}
with open("[Link]", "w") as f:
[Link](data, f)
🔸 Reading from a JSON File
import json
with open("[Link]", "r") as f:
result = [Link](f)
print(result)
Output:
{'name': 'Nav', 'age': 20, 'city': 'Delhi'}
💡 9. Key Points to Remember
Always close files after reading or writing (or use with block).
Use "r" for reading, "w" for writing, "a" for appending.
Text files store normal text; binary files store data in byte form.
pickle → stores Python objects (serialization).
csv → used for spreadsheets or tabular data.
json → used for structured and web data exchange.
🧠 10. Real-life Examples
File Type
Situation
Used
Saving user details or notes Text file
Saving profile pictures Binary file
Saving Python list or dictionary
Pickle file
permanently
Storing student marks in table format CSV file
Sharing data between applications or
JSON file
websites
📊 DATA VISUALIZATION IN
PYTHON
🌟 1. Introduction
Data Visualization means representing data in graphical or pictorial form.
It helps us to see patterns, trends, and relationships in data that are not easily
visible in tables or numbers.
For example:
bution of ages using a histogram.
We can show student marks in a bar chart.
We can show daily temperature in a line chart.
We can show how a total is divided using a pie chart.
We can show distribute can show 3D surfaces or relations using a 3D plot.
🎯 2. Importance of Data Visualization
Makes data easy to understand.
Helps in decision making by seeing clear trends.
Saves time — visuals are quicker to interpret than tables.
Helps in identifying errors, patterns, and relationships in data.
Used in Data Science, Machine Learning, and Business Analytics.
Makes presentations more effective and professional.
🧩 3. Libraries Used for Visualization in
Python
The most commonly used Python libraries for visualization are:
Library Purpose / Use
Matplotli
Basic 2D and 3D plotting. Oldest and most popular.
b
Built on Matplotlib, gives beautiful and statistical
Seaborn
graphs.
Plotly Used for interactive and web-based graphs.
Pandas
Easy plotting directly from DataFrames.
Plot
In this topic, we mainly use Matplotlib.
⚙️4. Installing and Importing Matplotlib
🧠 Installation (only once):
pip install matplotlib
📥 Importing in your Python program:
import [Link] as plt
We write plt as a short name for [Link].
📈 5. Creating a Simple Line Graph (2D
Plot)
A 2D plot means a graph drawn between two variables — one on the X-axis
(horizontal) and one on the Y-axis (vertical).
Example:
import [Link] as plt
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
[Link](x, y)
[Link]("Simple Line Graph")
[Link]("X Axis - Numbers")
[Link]("Y Axis - Doubled Values")
[Link]()
Explanation:
[Link](x, y) → draws a line graph.
[Link]() → adds title.
[Link]() and [Link]() → add axis labels
[Link]() → displays the graph.
Output:
A straight line showing how Y increases as X increases.
Customizing Line Style
You can change color, style, and marker shapes.
[Link](x, y, color='red', linestyle='--', marker='o')
[Link]("Customized Line Graph")
[Link]()
Option Example Value Use
color 'blue', 'red', 'green' Line color
Dashed, solid,
linestyle '--', '-', ':'
dotted
marker 'o', '*', 's' Points on data
📊 6. Bar Graph
Bar Graphs are used to compare values between categories.
Example:
import [Link] as plt
subjects = ['Math', 'Science', 'English', 'History']
marks = [88, 92, 75, 85]
[Link](subjects, marks, color='skyblue')
[Link]("Student Marks")
[Link]("Subjects")
[Link]("Marks")
[Link]()
Explanation:
Each bar represents one subject.
The height shows the marks.
📊 Horizontal Bar Graph
[Link](subjects, marks, color='orange')
[Link]("Horizontal Bar Chart")
[Link]()
🧮 7. Scatter Plot
Scatter plots show the relationship between two numerical variables.
Example:
import [Link] as plt
x = [10, 20, 30, 40, 50]
y = [8, 25, 18, 35, 30]
[Link](x, y, color='purple', marker='*')
[Link]("Scatter Plot Example")
[Link]("X values")
[Link]("Y values")
[Link]()
Explanation:
Each point shows a data pair (x, y).
Helps in studying correlation or trends.
🧭 8. Histogram
A Histogram shows the frequency distribution of numerical data —
i.e., how many values fall within certain ranges (called bins).
Example:
import [Link] as plt
ages = [10, 22, 45, 33, 27, 19, 35, 29, 41, 50, 23, 37, 40]
[Link](ages, bins=5, color='lightcoral', edgecolor='black')
[Link]("Age Distribution Histogram")
[Link]("Age Range")
[Link]("Number of People")
[Link]()
Explanation:
bins=5 divides the data into 5 groups.
Histogram helps to visualize data spread, e.g., exam marks or population ages.
🥧 9. Pie Chart
A Pie Chart shows how a total is divided into parts or percentages.
Example:
import [Link] as plt
activities = ['Study', 'Sleep', 'Play', 'Eat']
hours = [6, 8, 4, 6]
[Link](hours, labels=activities, autopct='%1.1f%%',
colors=['gold','lightblue','lightgreen','pink'])
[Link]("Daily Routine of a Student")
[Link]()
Explanation:
Each slice = one activity.
autopct='%1.1f%%' shows the percentage on the pie.
colors defines custom colors.
Output:
A circle divided into four colorful slices with percentage labels.
🍕 Exploding (Highlighting) a Slice
[Link](hours, labels=activities, autopct='%1.1f%%',
explode=[0,0.1,0,0], shadow=True)
[Link]("Pie Chart with Explode Effect")
[Link]()
Explanation: The “Sleep” part pops out to highlight it.
📉 10. Multiple Plots on Same Graph
You can show more than one line in a single graph.
Example:
import [Link] as plt
x = [1, 2, 3, 4, 5]
y1 = [10, 20, 30, 40, 50]
y2 = [5, 10, 15, 20, 25]
[Link](x, y1, label="High Marks", color='green', marker='o')
[Link](x, y2, label="Low Marks", color='red', marker='x')
[Link]("Two Lines in One Graph")
[Link]("X axis")
[Link]("Y axis")
[Link]() # To display labels
[Link]()
Output:
Two lines with different colors and labels.
🔷 11. Subplots (Many Graphs in One
Window)
You can show multiple graphs in a single window using [Link]().
Example:
import [Link] as plt
x = [1, 2, 3, 4, 5]
y = [10, 20, 30, 40, 50]
[Link](2, 2, 1)
[Link](x, y)
[Link]("Line")
[Link](2, 2, 2)
[Link](x, y)
[Link]("Bar")
[Link](2, 2, 3)
[Link](y)
[Link]("Histogram")
[Link](2, 2, 4)
[Link](y, labels=x)
[Link]("Pie")
plt.tight_layout()
[Link]()
Explanation:
2 rows × 2 columns = 4 graphs in one window.
tight_layout() avoids overlapping of titles and labels.
🌈 12. 3D Plotting
We can also make 3D plots using Matplotlib’s 3D toolkit.
Step 1: Import Required Modules
from mpl_toolkits.mplot3d import Axes3D
import [Link] as plt
import numpy as np
Step 2: Create Data and Plot
fig = [Link]()
ax = fig.add_subplot(111, projection='3d')
x = [Link](-5, 5, 100)
y = [Link](-5, 5, 100)
X, Y = [Link](x, y)
Z = [Link]([Link](X**2 + Y**2))
ax.plot_surface(X, Y, Z, cmap='viridis')
ax.set_title("3D Surface Plot")
ax.set_xlabel("X Axis")
ax.set_ylabel("Y Axis")
ax.set_zlabel("Z Axis")
[Link]()
Explanation:
[Link]() creates grid data for 3D plotting.
plot_surface() makes the 3D surface.
cmap='viridis' adds color shading.
Output:
A colorful 3D wave-like surface.
💡 13. Adding Labels, Titles, and Legends
Command Use
[Link]("Graph Title") Adds title
[Link]("X Axis Label") Adds X-axis name
[Link]("Y Axis Label") Adds Y-axis name
[Link]() Displays the label names
[Link](True) Adds grid lines for clarity
Example:
[Link](x, y, label="Growth", color='red')
[Link]("Growth Chart")
[Link]("Year")
[Link]("Value")
[Link]()
[Link](True)
[Link]()
📚 14. Summary Table of Common Plot
Types
Plot Type Function Purpose Example
To show trends over
Line Plot [Link]() Growth of marks
time
Bar Chart [Link]() To compare quantities Sales comparison
To show frequency
Histogram [Link]() Age or marks
distribution
To show parts of a
Pie Chart [Link]() Market share
whole
Scatter To show relation
[Link]() Height vs weight
Plot between two variables
3D Mathematical
ax.plot_surface() To show 3D data
Surface surfaces
To show multiple Line + Bar + Pie
Subplots [Link]()
graphs together
🧮 15. Difference Between 2D and 3D
Plotting
Featur
2D Plot 3D Plot
e
Axes X and Y X, Y, and Z
Simple comparison or Complex data
Use
trend visualization
Functio
[Link]() ax.plot_surface()
n
Exampl
Line chart, bar graph 3D surface, 3D scatter
e
🌍 16. Real-Life Applications
Field Visualization Use
Education Show student performance trends
Business Compare sales, profits, expenses
Represent experiments and
Science
simulations
Data Science Analyze datasets visually
Web
Dashboard charts and analytics
Development
Stock market graphs, ROI
Finance
comparison
🧠 17. Summary / Key Points
✅ Data visualization helps to see and understand data easily.
✅ Matplotlib is the most popular Python library for plotting.
✅ 2D plots include line, bar, pie, histogram, scatter.
✅ 3D plots help to show complex data surfaces.
✅ Use labels, titles, and legends for clear graphs.
✅ You can plot multiple graphs using subplots.
✅ Graphs make reports and analysis more effective and attractive.