0% found this document useful (0 votes)
2 views28 pages

Python Unit 4

The document explains file handling in Python, highlighting the importance of storing data permanently using files instead of temporary RAM. It covers various file modes, examples of reading and writing data, and introduces the Pandas library for data analysis and manipulation. Additionally, it details the structure of Series and DataFrames in Pandas, along with basic data analysis techniques.
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)
2 views28 pages

Python Unit 4

The document explains file handling in Python, highlighting the importance of storing data permanently using files instead of temporary RAM. It covers various file modes, examples of reading and writing data, and introduces the Pandas library for data analysis and manipulation. Additionally, it details the structure of Series and DataFrames in Pandas, along with basic data analysis techniques.
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

Problem Without File Handling

• In Python, when we store data


in variables, it stays only in RAM
(temporary memory).
• Once the program stops, the data
is lost.
• Example:
name = "Rahul"
marks = 85
• Data will disappear after program
ends.
What is File Handling?
• File handling means storing data inside a file.
• Files are stored on the hard disk → so data
is permanent.
Python provides functions like:
• open()
• read()
• write()
• close()
Why Do We Need
File Handling?
To save data permanently.

To reuse data later without re-


entering it.

To share data between programs.

To manage large amounts of


data easily.
Real-Life Examples
• Student Records → marks stored in files.
• ATM Machines → every transaction saved in a log file.
• Hospitals → patient history stored as files.
• Shopping Apps → orders and bills saved in files.
Different Modes
of File Handling

• File mode tells Python how


you want to open a file.
• Examples: read data, write
new data, append data.
| Mode | What it Does | Example Use |
| ---- | ---------------------------------- | ------------------------ |
| `r` | Read only (file must exist) | Reading student marks |
| `w` | Write only (new file or overwrite) | Saving exam results |
| `a` | Append (add at end of file) | Adding new orders to log |
| `r+` | Read & write (file must exist) | Updating data in file |
| `w+` | Write & read (overwrite file) | Create new report & read |
| `a+` | Append & read (create if missing) | Add entries & read data
|
Example Code

# Open file in write mode


f = open("[Link]", "w")
[Link]("Rahul: 85\n")
[Link]("Anita: 90\n")
[Link]()

# Open file in read mode


f = open("[Link]", "r")
print([Link]())
[Link]()
Read/Write Text and Numbers to/from a File
Writing Text to a File
• Use open() with write (w) or append (a) mode
• Use write() to save text
• Example:
f = open("[Link]", "w")
[Link]("Rahul\n")
[Link]("Anita\n")
[Link]()

This will create a file [Link] with names.


Reading Text from a File

• Use open() with read (r) mode


• Use read() or readlines() to get content
Example:
f = open("[Link]", "r")
print([Link]())
[Link]()
Output:
Rahul
Anita
Writing Numbers to a File

Numbers need to be converted to string using str()


Example:
marks = [85, 90, 78]
f = open("[Link]", "w")
for m in marks:
[Link](str(m) + "\n")
[Link]()
This saves each number on a new line in [Link].
Reading Numbers from a File
f = open("[Link]", "r")
numbers = [Link]()
numbers = [int([Link]()) for n in numbers]
print(numbers)
[Link]()

Output:
[85, 90, 78]
Directories on a Disk
What is a Directory?
• A directory (or folder) is a place on
your computer where files are stored.
• Helps to organize files.
• Example:
C:/Users/Nitika/Documents/
├─ [Link]
├─ [Link]
└─ projects/
Absolute vs Relative Path

• Absolute Path: Full path of a file from the


root of the disk.
"C:/Users/Nitika/Documents/[Link]”
• Relative Path: Path of a file relative to the
current working directory.
"[Link]"
Absolute vs Relative Path – Easy Explanation

1. Use a Real-Life Analogy


• Think of your computer like a house.
• Files = things in the house
• Folders = rooms
Absolute Path: Full address from the street (root) to the thing.
• Example:
C:/Users/Nitika/Documents/[Link]

Like saying: “Go to house number 10, 2nd floor, room 3, desk 2 →
take the notebook.”
Relative Path: Shorter, depends on where you are currently
standing.

• If you are already in Documents folder:


[Link]

Like saying: “I’m in the room, just take the notebook on desk 2.”
Using os Module
import os

# Current directory
print([Link]())

# List files/folders
print([Link]())

# Create a new folder


[Link]("NewFolder")

# Check if file exists


print([Link]("[Link]"))
What is Pandas?
Pandas is a Python library used for data analysis
and manipulation.
Name “Pandas” comes from “Panel Data”, which is
a term used in statistics.
It makes working with structured data (like tables in
Excel) easy and fast.
--With Pandas, you can:
Read and write data from files (CSV, Excel, JSON,
etc.)
Clean and organize data
Perform mathematical operations like sum, mean,
count
Filter, sort, and group data
Why Use Pandas?
• Handle large datasets efficiently
• Analyze data quickly
• Clean and filter data easily
• Perform calculations like average, sum, count
• Work with real-world data (students, sales, weather, stock market)
Use Cases (Real Life Examples):
• Teachers → Calculate average marks, find topper
• Business → Analyze sales data to see best-selling product
• Weather → Find hottest/coldest day
• Bank → Analyze transactions
a) Series
Main Data Structures • A Series is a one-dimensional array (like a single
in Pandas column of data).
• Each element in Series has an index (like row
number).
Example Concept:
• Think of a list of student marks: [85, 90, 78]
• Pandas stores it as Series → each mark has
an index (0,1,2).
Properties:
• 1D labeled array
• Can hold numbers, text, or dates
• Fast and easy to operate
b) DataFrame

• A DataFrame is a two-dimensional table (like Excel sheet).


• Contains rows and columns.
• Each column is a Series.
Example Concept:
| Name | Marks | Grade |
| ----- | ----- | ----- |
| Rahul | 85 | A |
| Anita | 90 | A+ |
| Sita | 78 | B |
• Rows → records
• Columns → fields
• Can store numbers, text, dates in different columns
• Reading and Writing Data
Pandas can read data from CSV, Excel,
JSON, SQL etc.
Commands:
• pd.read_csv("[Link]") → read CSV
• pd.read_excel("[Link]") → read
Excel
• df.to_csv("[Link]") → save
DataFrame to CSV
Basic Data Analysis in Pandas

Name, Maths, Science, English, Grade


• Rahul, 85, 80, 78, A
• Anita, 90, 95, 85, A+
• Sita, 78, 75, 82, B
• Amit, 92, 89, 90, A+
• Neha, 88, 92, 87, A
1. import pandas as pd
df = pd.read_csv("[Link]")
df

2. [Link]() # First 5 rows


[Link]() # Last 5 rows
[Link]() # Columns, non-null counts, data types
[Link]() # Summary stats for numeric columns

3. df["Maths"] # Only Maths column


df[["Name","Maths","English"]] # Multiple columns

[Link][0] # First row


[Link][1:4] # Rows 2 to 4 (index 1 to 3)
4. # Students who scored more than 85 in Maths
• df[df["Maths"] > 85]

• # Students with Grade A+


• df[df["Grade"] == "A+"]

5.# Sort by Maths marks descending


• df.sort_values("Maths", ascending=False)

• # Sort by Grade ascending


• df.sort_values("Grade")
6. # Average marks in each subject
• df[["Maths","Science","English"]].mean()

• # Total marks for each student


• df["Total"] = df["Maths"] + df["Science"] + df["English"]

• # Average total marks


• df["Total"].mean()

7. # Student with highest total marks


df[df["Total"] == df["Total"].max()]
8. # Average marks by Grade
[Link]("Grade")[["Maths","Science","English"]].mean()

# Count of students per Grade


df["Grade"].value_counts()

9. # Add Pass/Fail column (pass if average >= 80)


df["Average"] = df[["Maths","Science","English"]].mean(axis=1)[//axis=0(column
wise)
df["Result"] = df["Average"].apply(lambda x: "Pass" if x>=80 else "Fail")
df
[Link]() # First 5 rows
[Link]() # Last 5 rows
[Link] # Rows × Columns
[Link]() # Data types + nulls
[Link]() # Summary statistics
[Link] # Column names
[Link] # Row indexes

df["Maths"] # Single column


df[["Name","Science"]] # Multiple columns
[Link][0] # First row
[Link][0:3] # First 3 rows
[Link][0,"Maths"] # Specific row + column
• [Link]().sum()
• [Link](0)
• [Link]()
• df.to_csv("new_students.csv", index=False)
• df.to_excel("[Link]", index=False)
• [Link](3,"Maths")
• [Link](2,"Science")
• [Link](columns={"Maths":"Mathematics"}, inplace=True)
• [Link]("Total", axis=1)

You might also like