Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
31 views

Chapter 2 File Handling in Python (New NCERT Syllabus) (1) (1)

This document provides a comprehensive overview of file handling in Python, detailing the concepts of file types, methods for opening, reading, writing, and closing files, as well as the use of the Pickle module for serialization. It explains the differences between text and binary files, outlines various methods for reading and writing data, and includes example programs demonstrating these operations. Additionally, it covers how to access data randomly in files using tell() and seek() methods.

Uploaded by

Shahnawaz Khan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

Chapter 2 File Handling in Python (New NCERT Syllabus) (1) (1)

This document provides a comprehensive overview of file handling in Python, detailing the concepts of file types, methods for opening, reading, writing, and closing files, as well as the use of the Pickle module for serialization. It explains the differences between text and binary files, outlines various methods for reading and writing data, and includes example programs demonstrating these operations. Additionally, it covers how to access data randomly in files using tell() and seek() methods.

Uploaded by

Shahnawaz Khan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Chapter – 2

Data File Handling (New NCERT Syllabus)


Q1. What is a file, and why is it used in Python programming?
A file is a named location on secondary storage where data are permanently stored for later access.
Need for Files in Python:
 Variables in Python store data only temporarily during program execution.
 Files allow storing input, output, or processed data permanently.
 This avoids repetitive tasks like entering the same data repeatedly.
 Files are commonly used by organizations to store essential data like employee details, sales
records, and inventory.
Example:
 Python programs are saved as files with a .py extension on storage devices.
 Data (input and output) can also be saved into files for later use.
Files help achieve data reusability and storage efficiency.

Q2. What are the types of files? Explain briefly.


There are two main types of files in Python:
1. Text Files:
 Consist of human-readable characters (alphabets, numbers, special symbols).
 Examples: Files with extensions like .txt, .py, and .csv.
 Stored internally as bytes (0s and 1s), but displayed as characters using encoding
schemes (e.g., ASCII, Unicode).
 Each line ends with an End of Line (EOL) character, such as newline (\n).
 Example: ASCII value 65 (binary: 1000001) represents the letter 'A'.
2. Binary Files:
 Consist of non-human readable data (like images, videos, audio, or executable files).
 Bytes represent actual content rather than ASCII values.
 Requires specific programs (like media players) to access them.
 Example: Opening a binary file in a text editor will show garbage values.
 Even a small bit change can corrupt the entire file.
Python allows reading and writing of both text and binary files.

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.

3. Using with Clause:

 A simpler way to open and close a file automatically.


 Syntax: with open(file_name, access_mode) as file_object:
# File operations

 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

 If no argument or a negative number is specified, it reads a complete line:


myobject = open("myfile.txt", 'r')
print(myobject.readline())
myobject.close()
Output:
'Hello everyone\n'

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']

 If splitlines() is used instead of split(), each line is returned as an element of


a list without being split into words:
for line in d:
words = line.splitlines()
print(words)
Output:
['Hello everyone']
['Writing multiline strings']
['This is the third line']

Q6. Program - Writing and Reading to a Text File.

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

print("Now reading the contents of the file:")


fobject = open("testfile.txt", "r")
for str in fobject: # Reading and printing each line
print(str)
fobject.close()
Output:
RESTART: Path_to_file\Program2-1.py
Enter the contents to be written in the file:
roll_numbers = [1, 2, 3, 4, 5, 6]
Now reading the contents of the file:
roll_numbers = [1, 2, 3, 4, 5, 6]

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.

Q8. Program: Application of seek() and tell()


# Open file in read-write mode
file = open("testfile.txt", "r+")

# Read and display contents


print("Contents:", file.read())

# Show initial position


print("Initial Position:", file.tell())

# Move to the beginning


file.seek(0)
print("Position after reset:", file.tell())

# Move to 10th byte


file.seek(10)
print("Position at 10th byte:", file.tell())

# Read remaining data


print("Remaining Data:", file.read())

# 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.

1. Introduction to File Operations


 Explanation of various methods used for opening, closing, reading, and writing data
in a text file.
 Finding and moving the file object to a desired location.
 Working with practice.txt to perform basic operations.

2. Creating a File and Writing Data


 Usage of the open() method to create a text file by providing the filename and the
mode.
 Behavior of the open() function:
 Write Mode (w): Existing file contents are erased, and a new empty file is
created.
 Append Mode (a): New data is added after the existing content, and an
empty file is created if it doesn't exist.

Example: Program to create practice.txt and write data.


# Program to create a text file and add data
fileobject = open("practice.txt", "w+")
while True:
data = input("Enter data to save in the text file: ")
fileobject.write(data)
ans = input("Do you wish to enter more data? (y/n): ")
if ans == 'n':
break
fileobject.close()
Program Output:
RESTART: Path_to_file\Program2-3.py
Enter data to save in the text file: I am interested to learn about
Computer Science
Do you wish to enter more data? (y/n): y
Enter data to save in the text file: Py

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.

Program: Code to display data from a text file:


fileobject = open("practice.txt", "r")
str = fileobject.readline()
while str:
print(str)
str = fileobject.readline()
fileobject.close()

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.

Methods in Pickle module:


1. dump() method: Used for serializing (pickling) and writing Python objects into a binary
file.
Syntax: pickle.dump(data_object, file_object)
Example:
import pickle
listvalues = [1, "Geetika", 'F', 26]
fileobject = open("mybinary.dat", "wb")
pickle.dump(listvalues, fileobject)
fileobject.close()

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:

1) Writing Employee Records (Pickling):


import pickle
with open("empfile.dat", "ab") as bfile:
while True:
eno = int(input("Employee number: "))
ename = input("Employee Name: ")
salary = int(input("Salary: "))
pickle.dump([eno, ename, salary], bfile)
if input("Add more records (y/n)? ").lower() == 'n':
break
2) Reading Employee Records (Unpickling):
import pickle
with open("empfile.dat", "rb") as bfile:
try:
while True:
print(pickle.load(bfile))
except EOFError:
pass
Explanation:
 The dump() method stores the employee details as a list in the binary file empfile.dat.
 The load() method retrieves and displays each record.
 The EOFError exception handles the end of the file gracefully.

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

[11, 'Ravi', 32000]


[12, 'Farida', 45000]

***********************************

Chethan M B Arehalli | II PUC | Computer Science (New NCERT Syllabus) | Parikrma Junior College

You might also like