100% found this document useful (1 vote)
11 views22 pages

Python File Handling - Class 12 Computer Science

This document provides comprehensive notes on Python file handling, covering types of files, file modes, and methods for reading from and writing to text files. It includes practical examples and common patterns for file operations, as well as advanced topics like binary files and CSV handling. Key concepts such as file paths, numeric data in files, and random access methods are also discussed.

Uploaded by

bobamilkyt463
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
11 views22 pages

Python File Handling - Class 12 Computer Science

This document provides comprehensive notes on Python file handling, covering types of files, file modes, and methods for reading from and writing to text files. It includes practical examples and common patterns for file operations, as well as advanced topics like binary files and CSV handling. Key concepts such as file paths, numeric data in files, and random access methods are also discussed.

Uploaded by

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

Python File Handling - Complete Notes

Chapter: Data File Handling

1. Introduction to Files

 Data: Pieces of information used by users

 Files: Storage areas for data

 Types of files: Mainly 3 types (text, binary, CSV)

Text Files

 Consist of sequences of characters (ASCII/Unicode)

 Contain alphabets, numbers, symbols

 Have EOL (End of Line) character at each line (default: \n)

 Represent the end of a sentence where conversion takes place

 Human readable

File Modes

Mod
Purpose File Exists File Doesn't Exist File Pointer
e

FileNotFoundErro
r Read only Opens for reading Beginning
r

FileNotFoundErro
r+ Read + Write Opens for both Beginning
r

w Write only Overwrites content Creates new file Beginning

w+ Write + Read Overwrites content Creates new file Beginning

a Append only Retains content Creates new file End

a+ Append + Read Retains content Creates new file End


📊 File Modes Comparison:

Mode Read? Write? File Exists File Doesn't Exist File Pointer Starts At

r ✅ Yes ❌ No Opens ❌ Error Beginning

r+ ✅ Yes ✅ Yes Opens ❌ Error Beginning

w ❌ No ✅ Yes ❗ Overwrites ✅ Creates Beginning

w+ ✅ Yes ✅ Yes ❗ Overwrites ✅ Creates Beginning

a ❌ No ✅ Yes ✅ Appends ✅ Creates End

a+ ✅ Yes ✅ Yes ✅ Appends ✅ Creates End

- Overwriting means complete replacement - it deletes everything and starts


fresh.

🎯 Exam Memory Aid:


Think of a library book:

 r = Read book (can't write in it)

 r+ = Read & write notes (book must exist)

 w = New notebook (erases old one if exists)

 w+ = New notebook you can also read

 a = Add to diary (keep old entries)

 a+ = Add to diary & read old entries

📝 Important Exam Points:

1. r/r+ → File MUST exist (error if not)

2. w/w+ → DANGER! Deletes existing content

3. a/a+ → Always adds to end (use seek() to read)

4. + modes = Can do both read and write

5. Position matters! a+ starts at end, others at beginning


💡 Quick Decision Guide:

Need to... → Use mode:

 Just read → r

 Read and edit → r+

 Create new file (overwrite) → w

 Create new and read later → w+

 Add to end of file → a

 Add to end AND read → a+ (remember seek(0)!)

Opening and Closing Files

Syntax:

python

file_object = open('filename', 'mode')

# Operations...

file_object.close()

Example:

python

f = open('[Link]', 'r')

print('File opened')

[Link]()

Using with statement (Recommended):

python

with open('filename', 'mode') as file_object:

# Operations...

# File automatically closes

Reading from Text Files

1. read() - Read all content

python

# Q1: Write a program to read all content from [Link]


f = open('[Link]', 'r')

data = [Link]()

print(data)

[Link]()

2. read(size) - Read specific characters

python

# Q2: Write a program to read 7 characters from [Link]

f = open('[Link]', 'r')

data = [Link](7)

print(data)

[Link]()

3. readline() - Read single line

python

# Q3: Write a program to read a single line from [Link]

f = open('[Link]', 'r')

line1 = [Link]()

line2 = [Link]()

print(line1)

print(line2)

[Link]()

4. readlines() - Read all lines as list

python

# Q4: Write a program to read all data from [Link]

f = open('[Link]', 'r')

lines = [Link]()

print(lines) # Output: ['line1\n', 'line2\n', 'line3\n']

[Link]()

COMMON PATTERNS:
Task Method Check

Word starts with vowel read().split() word[0] in vowels

Line ends with period readlines() [Link]().endswith('.')

Find specific word read().split() if word == "the":

Count uppercase letters read() [Link]()

Longest word read().split() max(words, key=len)

Question about WORDS? → read() + split()

Question about LINES? → readlines()

Question about ENTIRE TEXT? → read()

Large file? → readline() in loop

Q) Read lines that end with a period/fullstop.

f=open("[Link]",'r')

def display_fullstop():

count=0

lines=[Link]()

for line in lines:

if [Link]().endswith('.'):

count+=1

print(count)

display_fullstop()

Writing to Text Files


1. write(string) - Write string to file

python

# Q5: Write a program to write strings to a file

f = open('[Link]', 'w')

[Link]('We are writing\n')

[Link]('Adding to file\n')

print('Data added')

[Link]()

2. writelines() - Write sequence data

python

# Q6: Write a program to write a list to file

f = open('[Link]', 'w')

L = ['apple\n', 'orange\n', 'banana']

[Link](L)

print('Data added')

[Link]()

3. Appending to file

python

# Q7: Write a program to append data to file

f = open('[Link]', 'a')

L = ['kiwi\n', 'lemon\n', 'pears']

[Link](L)

print('Data added')

[Link]()

File Paths

Relative vs Absolute Path

python

# Absolute path example

f = open('C:\\local\\programs\\[Link]', 'w')
x = 56

[Link](str(x))

[Link]()

Numeric Data in Files

Example 1: Writing numbers

python

# Q8: Write a program to write numeric data to file

f = open('[Link]', 'w')

x = 56

y = 76

[Link](str(x + y))

[Link]()

Example 2: User input to file

python

# Q9: Write a program to add two numbers and save to file

f = open('[Link]', 'w')

x = int(input('Enter number 1: '))

y = int(input('Enter number 2: '))

sum_xy = x + y

[Link]('First number: ' + str(x) + '\n')

[Link]('Second number: ' + str(y) + '\n')

[Link]('Sum: ' + str(sum_xy))

[Link]()

Note:
[Link]("Single string") # ✓ One string

[Link]("Value: " + str(num)) # ✓ Concatenated string

[Link](f"Value: {num}") # ✓ f-string (one string)

[Link]("Line 1\n" + "Line 2\n") # ✓ Still one string


Text File Analysis - Key Concepts

 Word: Use read() + split()

 Character/Symbol: Use readlines()

 Line ending: Check line[-2]

 Line starting: Check line[0]

 Word ending: Check word[-1]

Practice Programs

1. Lines starting with specific letter

python

# Q10: Count lines starting with 'K' in [Link]

f = open('[Link]', 'r')

count = 0

lines = [Link]()

for line in lines:

if line[0] == 'K':

count += 1

print(line)

print('Total lines:', count)

[Link]()

2. Using with statement

python

# Q11: Read file using with statement

with open('[Link]', 'r') as f:

data = [Link]()

print(data)

Random Access in Files

1. tell() - Get current position


python

# Q12: Demonstrate tell() method

f = open('[Link]', 'r')

print([Link]()) # Shows current position

[Link]()

2. seek() - Change position

python

# Q13: Demonstrate seek() method

f = open('[Link]', 'r')

print([Link]()) # Position: 0

[Link](5, 0) # Move 5 bytes from beginning

print([Link]()) # Position: 5

[Link]()

Seek modes:

 0: Beginning of file (default)

 1: Current position

 2: End of file

python

# Example with writing

f = open('[Link]', 'w')

[Link]('We are writing\n')

[Link]('Hello\nWorld')

print('Data added')

[Link]()

Advanced Text File Operations

1. Lines ending with period

python

# Q14: Find lines ending with '.' in [Link]

f = open('[Link]', 'r')
count = 0

lines = [Link]()

for line in lines:

if line[-2] == '.':

print(line)

count += 1

print('Count:', count)

[Link]()

2. Lines starting with T/t

python

# Q15: Count lines starting with T/t in [Link]

f = open('[Link]', 'r')

count = 0

lines = [Link]()

for line in lines:

if line[0] == 'T' or line[0] == 't':

print(line)

count += 1

print('Count:', count)

[Link]()

3. Count specific words

python

# Q16: Count words "the" and "this" in [Link]

f = open('[Link]', 'r')

count = 0

data = [Link]()

words = [Link]()

for word in words:

if word == 'the' or word == 'this':

print(word)
count += 1

print('Count:', count)

[Link]()

4. Function version

python

# Q17: Function to count "the" and "this"

def words():

f = open('[Link]', 'r')

count = 0

data = [Link]()

words = [Link]()

for word in words:

if word == 'the' or word == 'this':

print(word)

count += 1

print('Count:', count)

[Link]()

words()

5. Count "ME" or "MY"

python

# Q18: Count "ME" or "MY" in [Link]

def countwords():

f = open('[Link]', 'r')

count = 0

data = [Link]()

words = [Link]()

for word in words:

if word == 'ME' or word == 'MY':

print(word)
count += 1

print('Count:', count)

[Link]()

countwords()

6. Lines with 'a' as last character

python

# Q19: Count lines having 'a' as last character

with open('[Link]', 'r') as f:

count = 0

lines = [Link]()

for line in lines:

if line[-2] == 'a':

print(line)

count += 1

print('Count:', count)

7. Words longer than 5 characters

python

# Q20: Display words longer than 5 characters

def long_words():

f = open('[Link]', 'r')

count = 0

data = [Link]()

words = [Link]()

for word in words:

if len(word) >= 5:

print(word)

count += 1

print(f'Words > 5 chars: {count}')

[Link]()
long_words()

8. Lines containing specific word

python

# Q21: Display lines containing 'vote'

f = open('[Link]', 'r')

count = 0

lines = [Link]()

for line in lines:

if 'vote' in line:

print(line)

count += 1

print(f'Lines with "vote": {count}')

[Link]()

9. Line with maximum vowels

python

# Q22: Find line with maximum vowels

def max_vowels_line():

f = open('[Link]', 'r')

max_vowels = 0

max_line = ''

vowels = 'aeiouAEIOU'

lines = [Link]()

for line in lines:

vowel_count = 0

for char in line:

if char in vowels:

vowel_count += 1
if vowel_count > max_vowels:

max_vowels = vowel_count

max_line = line

[Link]()

print(f'Line: {max_line}')

print(f'Vowel count: {max_vowels}')

max_vowels_line()

10. Words starting/ending with vowel

python

# Q23: Words starting OR ending with vowel

f = open('[Link]', 'r')

data = [Link]()

words = [Link]()

vowels = 'aeiouAEIOU'

for word in words:

if word[0] in vowels or word[-1] in vowels:

print(word, end=' ')

print()

[Link]()

11. Display sentences separately

python

# Q24: Display each sentence in separate line

def showlines():

f = open('[Link]', 'r')

data = [Link]()

sentence = ''

for char in data:

sentence += char
if char in '.!?':

print([Link]())

sentence = ''

[Link]()

showlines()

12. Count uppercase/lowercase

python

# Q25: Count uppercase and lowercase letters

def c_words():

f = open('[Link]', 'r')

data = [Link]()

upper_count = 0

lower_count = 0

for char in data:

if [Link]():

upper_count += 1

elif [Link]():

lower_count += 1

print(f'Uppercase: {upper_count}')

print(f'Lowercase: {lower_count}')

[Link]()

c_words()

Binary Files

Pickle Module

 Serialization/Pickling: Object → Byte stream


 Deserialization/Unpickling: Byte stream → Object

 Extension: .dat or .bin

 Modes: rb, rb+, wb, wb+, ab, ab+

python

import pickle

# Writing: [Link](object, file)

# Reading: object = [Link](file)

Example 1: Write list to binary file

python

# Q26: Write list to binary file

import pickle

def write_list():

L = [1, 2, 3, 4, 5, 6]

f = open('[Link]', 'wb')

[Link](L, f)

print('Data added')

[Link]()

write_list()

# Reading back

f = open('[Link]', 'rb')

data = [Link](f)

print(data)

[Link]()

Example 2: Write dictionary

python

# Q27: Write dictionary to binary file


import pickle

data_dict = {'India': 'Delhi', 'UAE': 'Abu Dhabi', 'Qatar': 'Doha'}

f = open('[Link]', 'wb')

[Link](data_dict, f)

print('Data added')

[Link]()

# Reading back

f = open('[Link]', 'rb')

data = [Link](f)

print(data)

[Link]()

Example 3: Append multiple records

python

# Q28: Append student records to binary file

import pickle

records = []

while True:

rollno = int(input('Enter roll number: '))

name = input('Enter name: ')

marks = int(input('Enter marks: '))

record = [rollno, name, marks]

[Link](record)

choice = input('Continue? (y/n): ')

if [Link]() == 'n':

break
# Write all records

f = open('[Link]', 'wb')

[Link](records, f)

print('Data added')

[Link]()

# Read and display

f = open('[Link]', 'rb')

data = [Link](f)

for record in data:

rollno, name, marks = record

print(f'Roll No: {rollno}, Name: {name}, Marks: {marks}')

[Link]()

CSV Files

 CSV: Comma Separated Values

 Similar to text files, but values separated by commas

 Extension: .csv

 Module: import csv

 Return type: List of strings

Reading CSV Files

import csv

Eg:

f=open ('[Link]','r')

creader=[Link] (f)

for i in creader:

print (i)

[Link] ()|

Write row = to write 1 row;


Eg of output:

Adm_no,S_name,Percent

5313,Hayay,89.0

# Q29: Read CSV file contents

import csv

f = open('[Link]', 'r')

csv_reader = [Link](f)

for row in csv_reader:

print(row)

[Link]()

# Using with statement

with open('[Link]', 'r') as f:

csv_reader = [Link](f)

for row in csv_reader:

print(row)

Count records in CSV

python

# Q30: Count records in CSV file

import csv

f = open('[Link]', 'r')

csv_reader = [Link](f)

count = 0

for row in csv_reader:

count += 1

print(f'Total rows: {count}')


[Link]()

Count excluding header

python

# Q31: Count records excluding header

import csv

f = open('[Link]', 'r')

csv_reader = [Link](f)

count = len(list(csv_reader)) - 1 # Exclude header

print(f'Records (excl. header): {count}')

[Link]()

# Alternative using line_num

f = open('[Link]', 'r')

csv_reader = [Link](f)

for row in csv_reader:

if csv_reader.line_num == 1: # Skip header

continue

# Process data

[Link]()

Search in CSV

python

# Q32: Search student by name

import csv

name_to_search = input('Enter name to search: ')

f = open('[Link]', 'r')

csv_reader = [Link](f)

found = False

for row in csv_reader:


if row[2] == name_to_search: # Assuming name is in 3rd column

print(row)

found = True

break

if not found:

print('Record not found')

[Link]()

Writing to CSV

python

# Q33: Write data to CSV file

import csv

headers = ['SID', 'SName', 'SMarks']

rows = [['1', 'Raja', '100'],

['2', 'Ramees', '99'],

['3', 'Haya', '100']]

f = open('[Link]', 'w', newline='')

csv_writer = [Link](f, delimiter=',')

csv_writer.writerow(headers)

csv_writer.writerows(rows)

print('Data added')

[Link]()

Key Points to Remember

1. Always close files or use with statement

2. Text mode for text files, binary mode for binary files

3. CSV files use comma as default delimiter

4. Pickle for object serialization

5. File pointer positions matter for read/write operations


6. Exception handling is important for file operations

Common File Operations Summary

Operatio
Text File Binary File CSV File
n

read(), readline(), readlines(


Read [Link]() [Link]()
)

Write write(), writelines() [Link]() [Link]()

Append Mode 'a' Mode 'ab' Mode 'a'

Position seek(), tell() seek(), tell() Not typically used

Note: These notes cover the complete file handling portion for CBSE Class 12 Computer Science.
Practice each program type thoroughly for exam preparation.

You might also like