File Handling in Python - Class 12 Computer Science - Chapter 2 - Notes, NCERT Solutions & Extra Questions
Renews every month. Cancel anytime
Your personal doubt-solving assistant
Chatterbot AI gives you 100% accurate answers to your questions in an instant.
Notes - File Handling in Python | Class 12 NCERT | Computer Science
Comprehensive Guide to File Handling in Python for Class 12 Students
File handling in Python is an essential skill, especially for Class 12 students learning to manage data efficiently. This guide offers a detailed exploration of file handling concepts, techniques, and best practices.
Introduction to File Handling in Python
File handling refers to the process of creating, opening, reading, writing, and closing files. It is a fundamental aspect of programming that allows you to maintain and manipulate data for various applications.
Types of Files in Python
Text Files
Text files contain human-readable characters. Examples include .txt
, .py
, and .csv
files. They are easily accessible using any text editor.
Binary Files
Binary files consist of non-human-readable characters and symbols and often hold data like images, audio, videos, and executable files.
Which of the following file types is considered a text file in Python?
Opening and Closing a Text File
Using the open()
Function
To open a file in Python, use the open()
function with the syntax:
file_object = open(file_name, access_mode)
This function returns a file object, which you can use to perform various file operations.
Closing Files
It’s crucial to close a file after operations to free up system resources. Use the close()
method:
file_object.close()
What is the purpose of the close() method in file handling in Python?
Writing to a Text File
Using the write()
Method
The write()
method writes a single string to a file:
file_object.write("Hello, World!\n")
Using the writelines()
Method
For writing multiple strings, use the writelines()
method:
lines = ["Line1\n", "Line2\n"]
file_object.writelines(lines)
Reading from a Text File
Using the read()
Method
This method reads a specified number of bytes from a file:
content = file_object.read(10)
Using the readline()
Method
The readline()
method reads one complete line from a file:
line = file_object.readline()
Using the readlines()
Method
The readlines()
method reads all the lines in a file and returns them as a list:
lines = file_object.readlines()
Which method is used to read a single complete line from a text file in Python?
Understanding File Access Modes
Different access modes control how a file is opened and manipulated:
r
: Read-only mode.w
: Write-only mode. Overwrites the file if it exists or creates a new one.a
: Append mode. Writes data at the end of the file.r+
: Read and write mode.w+
: Write and read mode. Overwrites the file if it exists or creates a new one.a+
: Append and read mode.
Creating and Traversing a Text File
Creating a New File
To create a file, use the open()
method with "w" mode:
file_object = open("newfile.txt", "w")
Traversing a File
To traverse and read from a file:
file_object = open("newfile.txt", "r")
line = file_object.readline()
while line:
print(line)
line = file_object.readline()
file_object.close()
Setting Offsets in a File
Using the tell()
Method
This method returns the current file object position:
position = file_object.tell()
Using the seek()
Method
The seek()
method moves the file object to a specified position:
file_object.seek(10, 0)
Which method in Python is used to move the file object to a specified position within a file?
Working with Binary Files
Understanding how to handle binary files is crucial for dealing with non-text data like images or video. Binary files are accessed using similar methods but in binary mode ("rb", "wb" etc.).
The Pickle Module
The Pickle module is used for serialising (pickling) and de-serialising (unpickling) Python objects, making it possible to save complex data types like lists and dictionaries.
The dump()
Method
This method serialises Python objects into a binary file:
import pickle
data = {"name": "John", "age": 30}
with open("data.pkl", "wb") as file:
pickle.dump(data, file)
The load()
Method
To deserialise and read data:
with open("data.pkl", "rb") as file:
data = pickle.load(file)
Which method in Python would you use to read all the lines from a text file and return them as a list?
Exception Handling in File Operations
It's essential to manage exceptions to prevent your program from crashing due to file operation errors. Using try-except blocks will help:
try:
file_object = open("file.txt", "r")
content = file_object.read()
file_object.close()
except FileNotFoundError:
print("File not found.")
Which method is used to move the file object to a specified position in a file?
Summary and Best Practices
To summarise, file handling in Python involves several key operations: opening, reading, writing, closing files, and managing data types. Best practices include:
Always close files after operations
Use the
with
statement for better resource managementHandle exceptions to make your code robust
By mastering these file handling techniques, Class 12 students can efficiently manage data in their Python applications.
This guide offers a thorough understanding of file handling in Python, equipping students with the knowledge to perform advanced file operations and manage data effectively.
graph LR
A[Open File] --> B{Read or Write?}
B --> |Read| C["Use read(), readline() or readlines()"]
B --> |Write| D["Use write() or writelines()"]
C --> E[Close File]
D --> E[Close File]
Key Concepts Flowchart
This flowchart summarises the basic flow of file handling operations in Python. It shows how you can open a file, either read or write to it, and then close the file, ensuring proper file management.
By following this comprehensive guide, students will gain a solid foundation in file handling, preparing them for more complex programming projects and professional development.
🚀 Learn more about Notes with Chatterbot AI
NCERT Solutions - File Handling in Python | NCERT | Computer Science | Class 12
Differentiate between:
a) text file and binary file
b) readline() and readlines()
c) write() and writelines()
a) Text File vs Binary File
Text File:
Consists of human-readable characters.
Can be opened and interpreted by any text editor.
Stores data in plain text where each byte represents a character (ASCII or Unicode).
Examples include files with extensions like
.txt
,.csv
,.py
, etc.
Binary File:
Consists of non-human-readable data.
Requires specific programs to interpret since they store data in a format that can only be understood by specific applications.
Stores data as encoded bytes representing compact data like images, videos, compiled programs.
Examples include
.exe
,.png
,.mp3
, etc.
b) readline() vs readlines()
readline():
Reads one complete line from a file at a time.
A line ends with a newline character (
\n
), and this method will read up to, and including, the newline character.Returns a string representing the line or an empty string if EOF is reached.
readlines():
Reads all lines in a file and returns them as a list of strings, where each string is a line from the file.
Useful for processing all lines together or iterating through lines with a loop easily.
c) write() vs writelines()
write():
Writes a specific string to a file and requires that string to be passed as an argument.
Does not automatically add newline characters at the end of the string; you need to include them manually.
Commonly used for writing a single piece of data or line at a time.
writelines():
Writes a list of strings to a file.
Does not add newline characters automatically; each string in the list needs to have the newline character if it is needed.
Suitable for writing multiple strings or lines at once from an iterable object like a list or tuple.
Write the use and syntax for the following methods:
a) open()
b) read()
c) seek()
d) dump()
a) open()
Use:
The open()
function is used to open a file and returns a file object, which serves as a link to a file residing on the system. Through this file object, we can read from or write to the file.
Syntax:
file_object = open(file_name, access_mode)
file_name
is a string representing the name or path of the file.access_mode
specifies the mode in which the file is opened, like 'r' for reading, 'w' for writing, etc.
b) read()
Use:
The read()
method is used to read content from an open file. It can read a specified number of characters (or bytes in binary files) from the file.
Syntax:
file_object.read(size)
size
is an optional integer argument. If specified, at mostsize
characters (in text mode) orsize
bytes (in binary mode) are read. If omitted or negative, the entire contents of the file will be read and returned.
c) seek()
Use:
The seek()
method is used to change the current file position in an open file. This is beneficial for manipulating a specific part of the file, and not just reading/writing sequentially.
Syntax:
file_object.seek(offset, whence=0)
offset
is the number of bytes to move the file pointer.whence
is optional and determines the reference point for theoffset
:0
(default) sets the file's beginning as the reference point,1
sets the current file position, and2
sets the file's end as the reference point.
d) dump()
Use:
The dump()
function is part of the pickle
module used for serializing "pickling" a Python object structure into a byte stream, which can then be written to a binary file. This method is used to save Python objects, such as dictionaries, lists, etc., for later retrieval.
Syntax:
pickle.dump(obj, file, protocol=None, *, fix_imports=True, buffer_callback=None)
obj
is the object to be serialized.file
is a binary file object opened for writing.protocol
and other parameters are optional and control the serialization protocol and behavior.
Write the file mode that will be used for opening the following files. Also, write the Python statements to open the following files:
a) a text file "example.txt" in both read and write mode
b) a binary file "bfile.dat" in write mode
c) a text file "try.txt" in append and read mode
d) a binary file "btry.dat" in read only mode.
a) Text File "example.txt" in Both Read and Write Mode
File Mode:
r+
Python Statement:
file_object = open("example.txt", "r+")
b) Binary File "bfile.dat" in Write Mode
File Mode:
wb
Python Statement:
file_object = open("bfile.dat", "wb")
c) Text File "try.txt" in Append and Read Mode
File Mode:
a+
Python Statement:
file_object = open("try.txt", "a+")
d) Binary File "btry.dat" in Read Only Mode
File Mode:
rb
Python Statement:
file_object = open("btry.dat", "rb")
Why is it advised to close a file after we are done with the read and write operations? What will happen if we do not close it? Will some error message be flashed?
It is advised to close a file after read and write operations because:
Free Resources: Closing a file frees up system resources that were allocated to handle file operations.
Ensure Data Integrity: It ensures that all data is properly written and saved to the file. This is because the close operation flushes any buffered output data to disk.
Avoid File Corruption: Helps prevent potential file corruption that may occur due to unsaved or partially saved data.
If you do not close a file:
Data might not be written to the file if it's still held in the buffer.
Resources remain locked by the application, which can lead to resource leaks, affecting system performance or limiting file accessibility.
No explicit error message will necessarily be flashed immediately if you don't close a file; the issues might manifest as I/O errors, data loss, or unexpected behavior in data access later on.
What is the difference between the following set of statements (a) and (b):
a)
P = open("practice.txt","r")
P.read(10)
b)
with open("practice.txt", "r") as P:
P.read()
The key differences between the provided Python code snippets (a) and (b) regarding file handling are:
a)
P = open("practice.txt","r")
P.read(10)
This code manually opens a file named
"practice.txt"
in read mode ("r"
).It reads the first 10 characters from the file.
The file is not explicitly closed in this snippet, which can lead to resource leakage if not handled properly elsewhere in the program.
b)
with open("practice.txt", "r") as P:
P.read()
This code uses a
with
statement to open the file, ensuring that the file is automatically closed when the block under thewith
statement is exited, regardless of how the block is exited (e.g., normal end of block, return, exception).It reads the entire contents of the file without limiting the number of characters (unlike the first example where only the first 10 characters are read).
with
provides better safety and management of file resources by handling opening and closing of files automatically.
Summary:
Code snippet a requires manual management of the file object and reads a limited number of characters.
Code snippet b handles the file more safely by automatically managing the file's closing and reads the whole file.
Write a command(s) to write the following lines to the text file named hello.txt. Assume that the file is opened in append mode.
" Welcome my class"
"It is a fun place"
"You will learn and play"
# Assuming the file 'hello.txt' is opened in append mode with the file object 'file_object'
# Writing the specified lines to the file 'hello.txt'
file_object.write("Welcome my class\n")
file_object.write("It is a fun place\n")
file,object.write("You will learn and play\n")
# Ensure to close the file after writing to it
file_object.close()
Write a Python program to open the file hello.txt used in question no 6 in read mode to display its contents. What will be the difference if the file was opened in write mode instead of append mode?
Python Program to Open and Display Contents of hello.txt
# Open the file hello.txt in read mode
with open('hello.txt', 'r') as file:
# Read the contents of the file
content = file.read()
# Display the contents
print(content)
Differences When Opened in Write Mode Instead of Append Mode
Append Mode (
'a'
): Ifhello.txt
is opened in append mode, any data written to the file is added to the end of the file without altering the existing content. Even if the program is executed multiple times, the content is just added, preserving previous data.Write Mode (
'w'
): Ifhello.txt
is opened in write mode, opening the file automatically erases all existing data within the file. If you write to it, you start with a blank file, essentially overwriting any previous contents. Each execution of the script in write mode starts with an empty file, meaning prior contents are lost.
In summary, using append mode is crucial if the goal is to retain existing data and add new data at the end, while write mode is used when you need to start with a fresh or empty file, disregarding any existing data.
Write a program to accept string/sentences from the user till the user enters “END” to. Save the data in a text file and then display only those sentences which begin with an uppercase alphabet.
Here's a Python program:
# Program to accept sentences and save to a text file
# Displays sentences starting with an uppercase letter
def is_start_uppercase(sentence):
return sentence[0].isupper()
# Open the file in write mode
with open("sentences.txt", "w") as file:
while True:
sentence = input("Enter a sentence (Type 'END' to stop): ")
if sentence == "END":
break
file.write(sentence + "\n")
# Read the file and display sentences that start with an uppercase letter
print("\nSentences starting with an uppercase alphabet:")
with open("sentences.txt", "r") as file:
for line in file:
if is_start_uppercase(line.strip()):
print(line.strip())
How to use this program:
Run the program.
Enter sentences as prompted. Type 'END' when done entering all sentences.
After typing 'END', the program will display all sentences from the file that begin with an uppercase letter.
Define pickling in Python. Explain serialization and deserialization of Python object.
Pickling in Python refers to the process of serializing a Python object structure into a byte stream, which can then be stored in a file, sent over a network, or used for any other purpose where a byte stream format is required. This process is facilitated by Python’s Pickle module.
Serialization
Serialization, also known as pickling, is the process of transforming a Python object (such as dictionaries, lists, or even instances of classes) into a byte stream. This serialized form of the object is suitable for storage in files or transmission over a network.
The primary function for serialization in the Pickle module is
pickle.dump()
, which dumps an object to a file-like object. Here is an example syntax:import pickle data = {'key': 'value'} with open('data.pickle', 'wb') as file: pickle.dump(data, file)
Deserialization
Deserialization, also known as unpickling, is the inverse process where the byte stream (from a binary file or bytes-like object) is converted back into an object hierarchy.
The main function for this in the Pickle module is
pickle.load()
, which loads an object from a file-like object. Here is an example syntax:import pickle with open('data.pickle', 'rb') as file: data = pickle.load(file)
Key points:
Serialization allows the conversion of complex Python objects to a byte format that can be easily stored or transmitted.
Deserialization retrieves the original Python objects from the serialization byte stream.
Security Warning: It's crucial to only unpickle data you trust, as the process can execute arbitrary code.
Write a program to enter the following records in a binary file:
|
|
|
|
|
|
|
|
Number of records to be entered should be accepted from the user. Read the file to display the records in the following format:
Item No:
Item Name :
Quantity:
Price per item:
Amount: ( to be calculated as Price * Qty)
import pickle
def write_records(filename):
with open(filename, 'wb') as bfile:
n = int(input("Enter the number of records to enter: "))
for i in range(n):
print(f"Record {i + 1}:")
item_no = int(input("\tItem No: "))
item_name = input("\tItem Name: ")
qty = int(input("\tQuantity: "))
price = float(input("\tPrice per item: "))
record = [item_no, item_name, qty, price]
pickle.dump(record, bfile)
def read_records(filename):
print("\nDisplaying stored records:")
with open(filename, 'rb') as bfile:
try:
while True:
record = pickle.load(bfile)
item_no, item_name, qty, price = record
amount = qty * price
print(f"Item No: {item_no}")
print(f"Item Name: {item_name}")
print(f"Quantity: {qty}")
print(f"Price per item: {price}")
print(f"Amount: {amount:.2f}")
print("-" * 40)
except EOFError:
pass
# Specify the file name for binary data storage
filename = "items_data.dat"
# Writing and reading the records
write_records(filename)
read_records(filename)
This program does the following:
Writing Records: The function
write_records
prompts the user to enter the number of records and corresponding details (Item No, Item Name, Quantity, Price). It then dumps these records into a binary file using thepickle
module.Reading Records: The function
read_records
reads the binary file usingpickle
and calculates theAmount
for each record by multiplyingPrice
andQty
. It then prints out the formatted data for review.The user is first asked to input data for each item, which is serialized into a binary file named
items_data.dat
. After writing, the file is read to display all the records, including the calculated amount for each item.
💡 Have more questions?
Ask Chatterbot AI