Chapter 2 File Handling in Python (New NCERT Syllabus) (1) (1)
Chapter 2 File Handling in Python (New NCERT Syllabus) (1) (1)
Q3. How do you open and close a file in Python? Explain with syntax.
1. Opening a File:
Python provides the open() function to open a file.
Syntax: file_object = open(file_name, access_mode)
Attributes of File Object:
file.closed: Returns True if the file is closed.
file.mode: Returns the mode in which the file was opened.
file.name: Returns the name of the file.
Chethan M B Arehalli | II PUC | Computer Science (New NCERT Syllabus) | Parikrma Junior College
Example: myObject = open("myfile.txt", "a+")
Opens myfile.txt in append and read mode. The file pointer is positioned at the end
of the file.
2. Closing a File:
close() method is used to close a file and release the memory.
Syntax: file_object.close()
Python ensures that any unsaved data is written to the file before closing it.
Once the block inside with is completed, the file closes automatically.
Example: with open("myfile.txt", "r+") as myObject:
content = myObject.read()
No need to call close() explicitly!
Q4: How can we write data to a text file in Python, and what are the differences between the
write() and writelines() methods?
In Python, data can be written to a text file using the write() or writelines() methods after opening
the file in write ('w') or append ('a') mode.
1. write() Method:
Used for writing a single string to the text file.
Returns the number of characters written.
To mark the end of a line, a newline character (\n) must be added manually.
Numeric data must be converted to strings using str() before being written.
Example Code:
myobject = open("myfile.txt", 'w')
myobject.write("Hey I have started using files in Python\n")
myobject.close()
Output (characters written): 41
Note: The data is first written to a buffer and later transferred to permanent storage when the
close() method is executed.
Chethan M B Arehalli | II PUC | Computer Science (New NCERT Syllabus) | Parikrma Junior College
2. writelines() Method:
Used for writing multiple strings at once.
Takes an iterable object (like a list or tuple) containing strings as input.
Does not return the number of characters written.
Example Code:
myobject = open("myfile.txt", 'w')
lines = ["Hello everyone\n", "Writing multiline strings\n", "This is
the third line"]
myobject.writelines(lines)
myobject.close()
Output in myfile.txt:
Hello everyone
Writing multiline strings
This is the third line
Q5: How can we read data from a text file in Python, and what are the different methods used
for reading data?
In Python, we can read data from a text file after opening it in “r”, “r+”, “w+”, or “a+” mode. There
are three main methods for reading data from a file:
1. read() Method:
This method reads the specified number of bytes from a file. If no argument or a negative
number is passed, it reads the entire file.
Syntax: file_object.read(n)
Example:
myobject = open("myfile.txt", 'r')
print(myobject.read(10)) # Reads 10 bytes
myobject.close()
Output:
Hello ever
2. readline() Method:
This method reads one complete line from the file, up to the newline (\n) character. It can
also read a specified number of bytes.
Example:
myobject = open("myfile.txt", 'r')
print(myobject.readline(10)) # Reads first 10 characters from the
first line
myobject.close()
Output:
Hello ever
Chethan M B Arehalli | II PUC | Computer Science (New NCERT Syllabus) | Parikrma Junior College
3. readlines() Method:
This method reads all lines and returns them as a list of strings, where each line ends with a
newline character (\n).
Example:
myobject = open("myfile.txt", 'r')
print(myobject.readlines())
myobject.close()
Output:
['Hello everyone\n', 'Writing multiline strings\n', 'This is the
third line']
Each string in the list represents a line from the file. We can split the lines into words
using the split() function:
for line in d:
words = line.split()
print(words)
Output:
['Hello', 'everyone']
['Writing', 'multiline', 'strings']
['This', 'is', 'the', 'third', 'line']
This program writes a user-input string to a file and then reads and displays the content of the file:
fobject = open("testfile.txt", "w") # Creating a data file
sentence = input("Enter the contents to be written in the file: ")
fobject.write(sentence) # Writing data to the file
fobject.close() # Closing the file
Chethan M B Arehalli | II PUC | Computer Science (New NCERT Syllabus) | Parikrma Junior College
Q7: How can we access data in a random fashion in Python, and what are the functions used for
setting offsets in a file?
In Python, to access data in a random (non-sequential) fashion, we can use the following functions:
1. tell() Method:
This method returns an integer representing the current byte position of the file object, measured from
the beginning of the file.
Syntax: file_object.tell()
2. seek() Method:
This method moves the file object to a specified position.
Syntax: file_object.seek(offset, [, reference_point])
offset: Number of bytes by which the file object is to be moved.
reference_point: Starting position to count the offset from. It can take the following values:
0 – Beginning of the file (default).
1 – Current position of the file.
2 – End of the file.
Example: file_object.seek(5, 0) moves the file object to the 5th byte from the beginning of the
file.
# Close file
file.close()
Output (Example):
Contents: roll_numbers = [1, 2, 3, 4, 5, 6]
Initial Position: 33
Position after reset: 0
Position at 10th byte: 10
Remaining Data: rs = [1, 2, 3, 4, 5, 6]
Chethan M B Arehalli | II PUC | Computer Science (New NCERT Syllabus) | Parikrma Junior College
Q9: Explain the concepts of creating and traversing a text file.
Q10: How can a file be traversed and its data displayed in Python?
To traverse a file and display its data, follow these steps:
Purpose: To read and display data stored in a text file.
Example: Referring to the file practice.txt (created earlier).
Opening the File:
o The file is opened in "r" mode, and reading starts from the beginning.
Output of Program:>>>
I am interested to learn about Computer Science
Python is easy to learn
Chethan M B Arehalli | II PUC | Computer Science (New NCERT Syllabus) | Parikrma Junior College
Explanation of the Program:
readline() reads one line at a time from the text file within the while loop.
The lines are displayed using print().
Once the end of the file is reached, readline() returns an empty string, causing the loop to
stop.
The file is then closed using close().
Q11: How can reading and writing operations be performed in Python using a single file object?
To perform both reading and writing operations using the same file object, the file can be opened in
"w+" mode, which allows writing and reading from the file.
Code:
fileobject = open("report.txt", "w+")
fileobject.write("I am a student of class XII\n")
fileobject.write("my school contact number is 4390xxx8\n")
fileobject.seek(0) # Move file object to the beginning
print(fileobject.read()) # Read and display the content
fileobject.close()
Explanation of Code:
The file report.txt is opened in "w+" mode.
Two sentences are written to the file using write().
seek(0) moves the file object to the beginning to allow reading from the start.
read() reads the entire content, which is displayed using print().
The file is closed using close().
Output:
I am a student of class XII
my school contact number is 4390xxx8
Q12: What is the Pickle module in Python, and how does it perform serialization and
deserialization?
The Pickle module in Python is used for serializing and deserializing Python objects.
Serialization (pickling) transforms Python objects into a byte stream to store in a binary file
or database or send over a network.
Deserialization (unpickling) is the reverse process that converts the byte stream back into
Python objects.
2. load() method: Used for deserializing (unpickling) and reading Python objects from a
binary file.
Syntax: store_object = pickle.load(file_object)
Chethan M B Arehalli | II PUC | Computer Science (New NCERT Syllabus) | Parikrma Junior College
Example:
import pickle
print("The data that were stored in file are: ")
fileobject = open("mybinary.dat", "rb")
objectvar = pickle.load(fileobject)
fileobject.close()
print(objectvar)
Output of Program:
The data that were stored in file are:
[1, 'Geetika', 'F', 26]
Q13: How can employee records be stored and retrieved using the Pickle module in Python?
Employee records can be written to and read from a binary file using the Pickle module with minimal
steps:
Output:
Employee number: 11
Employee Name: Ravi
Salary: 32000
Add more records (y/n)? y
Employee number: 12
Employee Name: Farida
Salary: 45000
Add more records (y/n)? n
***********************************
Chethan M B Arehalli | II PUC | Computer Science (New NCERT Syllabus) | Parikrma Junior College