0% found this document useful (0 votes)
70 views6 pages

File Handling For 12

The document provides a comprehensive overview of file handling in Python for CBSE Class 12 Computer Science, detailing types of files, file operations, and common methods. It includes examples of reading and writing files, managing file pointers, and handling exceptions. Additionally, it presents a set of programming questions categorized by difficulty to practice file handling concepts.
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)
70 views6 pages

File Handling For 12

The document provides a comprehensive overview of file handling in Python for CBSE Class 12 Computer Science, detailing types of files, file operations, and common methods. It includes examples of reading and writing files, managing file pointers, and handling exceptions. Additionally, it presents a set of programming questions categorized by difficulty to practice file handling concepts.
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
You are on page 1/ 6

File Handling for CBSE Class 12 (083 – Computer Science):

File Handling in Python

File handling is an essential concept in Python that allows programs to read, write, and manipulate
files. Files are used for persistent storage of data.

Types of Files

1. Text Files

o Contains human-readable characters (ASCII/Unicode).

o Stores data as a sequence of lines, separated by newline (\n).

o Example: .txt, .csv

2. Binary Files

o Contains data in binary (non-human-readable) format.

o Typically used for images, videos, audio files, or executable programs.

o Example: .png, .exe

File Operations

Python provides several built-in functions for file handling.

Opening a File

Files can be opened using the open() function.


Syntax:

file_object = open(filename, mode)

• filename: Name of the file to open.

• mode: Mode in which the file is opened.

File Modes

Mode Description

'r' Read-only mode (default).

'w' Write mode. Creates a new file or overwrites existing.

'a' Append mode. Adds data to the end of the file.

'r+' Read and write.


Mode Description

'w+' Write and read (overwrites file).

'a+' Append and read.

'b' Binary mode. Add 'b' with modes for binary files (e.g., 'rb', 'wb').

Closing a File

Always close the file to free up resources. Use the close() method.

file_object.close()

Reading from a File

1. read(size) – Reads size characters. If omitted, reads the entire file.


Example:

2. file = open("example.txt", "r")

3. content = file.read()

4. print(content)

5. file.close()

6. readline() – Reads one line at a time.


Example:

7. line = file.readline()

8. readlines() – Reads all lines and returns them as a list.


Example:

9. lines = file.readlines()

Writing to a File

1. write(string) – Writes a string to the file.


Example:

2. file = open("example.txt", "w")

3. file.write("Hello, World!")

4. file.close()

5. writelines(list) – Writes a list of strings to the file.


Example:

6. lines = ["Line 1\n", "Line 2\n"]

7. file.writelines(lines)

File Pointer
• The file pointer indicates the current position in the file.

• Use tell() to get the current position of the file pointer. Example:

• position = file.tell()

• print(position)

• Use seek(offset, from_what) to change the file pointer's position.

o offset: Number of bytes to move.

o from_what: Reference point (0: start, 1: current, 2: end). Example:

• file.seek(0) # Move to the beginning

With Statement

The with statement is used to automatically close a file after its usage.
Example:

with open("example.txt", "r") as file:

content = file.read()

print(content)

# No need to call file.close()

Working with Binary Files

Binary files handle data in binary format. Example (writing binary data):

with open("example.bin", "wb") as file:

file.write(b"Binary Data")

Example (reading binary data):

with open("example.bin", "rb") as file:

data = file.read()

print(data)

File Handling Exceptions

To handle errors during file operations, use try-except. Example:

try:

file = open("nonexistent.txt", "r")

content = file.read()
except FileNotFoundError:

print("File not found!")

finally:

file.close()

Applications of File Handling

1. Storing data for future reference (logs, configurations, etc.).

2. Reading and writing structured data (e.g., CSV files).

3. Persistent storage for programs (e.g., saving user data).

4. Transferring data in binary form (e.g., images, videos).

Commonly Used File Methods

Method Description

open() Opens a file.

close() Closes a file.

read(size) Reads specified size from the file.

readline() Reads one line from the file.

readlines() Reads all lines into a list.

write(string) Writes a string to the file.

writelines(list) Writes a list of strings to the file.

tell() Returns the current position of the file pointer.

seek(offset, from_what) Changes the file pointer's position.

This concise summary covers key concepts required for the CBSE Class 12 Computer Science board
exam. Let me know if you'd like to add practice questions or detailed examples!
Here are 20 programming questions based on File Handling for CBSE Class 12 (083 – Computer
Science):

Basic Questions

1. Write a Python program to create a text file named example.txt and write the following lines
into it:

2. Hello, this is line 1.

3. This is line 2.

4. Welcome to Python file handling.

5. Write a Python program to read and display the content of a file data.txt line by line.

6. Write a Python program to count the number of lines, words, and characters in a text file
named sample.txt.

7. Write a Python program to append the following data to an existing file notes.txt:

8. File handling is important for persistent storage.

9. Write a program to check if a file named myfile.txt exists. If it exists, display its content;
otherwise, create the file and write "File created successfully."

Intermediate Questions

6. Write a Python program to read a file marks.txt containing student names and marks, and
display only the names of students who scored above 90.

7. Write a Python program to create a text file numbers.txt, write integers from 1 to 20, and
then read and print only the even numbers.

8. Write a Python program to replace all occurrences of the word "old" with "new" in a file
named document.txt.

9. Write a Python program to calculate the frequency of each word in a text file words.txt.

10. Write a Python program to copy the content of source.txt to a new file named
destination.txt.

Advanced Questions

11. Write a Python program to read a text file story.txt and display all lines that start with the
letter "A".

12. Write a Python program to merge the contents of two files, file1.txt and file2.txt, into a new
file merged.txt.

13. Write a Python program to read a binary file image.dat and display its content in
hexadecimal format.
14. Write a Python program to write a list of numbers into a binary file data.dat, then read the
file and calculate the sum of the numbers.

15. Write a Python program to remove all blank lines from a file named notes.txt.

Practice with Exception Handling

16. Write a Python program to handle FileNotFoundError while trying to read a non-existent file
nonexistent.txt.

17. Write a Python program to safely open a file using a try-except-finally block, ensuring the file
is always closed, even if an error occurs.

Applications

18. Write a Python program to read student data (name, roll number, and marks) from a text file
students.txt and display the details of the student with the highest marks.

19. Write a Python program to read a CSV file products.csv containing product names and prices,
and display the details of products costing more than ₹500.

20. Write a Python program to read a file grades.txt containing student names and grades and
create two separate files: pass.txt (for grades ≥ 40) and fail.txt (for grades < 40).

These questions cover a range of difficulties and concepts, including reading/writing files, binary
files, text manipulation, exception handling, and file operations. Let me know if you need solutions or
additional questions!

You might also like