0% found this document useful (0 votes)
3 views43 pages

CHAPTER2 FileHandling 1

Chapter 2 discusses file handling in Python, explaining how files are used for permanent data storage and the basic operations like creating, reading, writing, and deleting files. It covers different file types, access modes, and methods for reading and writing data, including the use of the 'with' clause for automatic file closure. Additionally, the chapter introduces the Pickle module for serializing and deserializing Python objects.

Uploaded by

itsuddu143
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)
3 views43 pages

CHAPTER2 FileHandling 1

Chapter 2 discusses file handling in Python, explaining how files are used for permanent data storage and the basic operations like creating, reading, writing, and deleting files. It covers different file types, access modes, and methods for reading and writing data, including the use of the 'with' clause for automatic file closure. Additionally, the chapter introduces the Pickle module for serializing and deserializing Python objects.

Uploaded by

itsuddu143
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

CHAPTER 2

✓ A file is a named location on a secondary storage media


where data are permanently stored for later access.

✓ File handling means reading of data of file or writing data


into file using python program.

✓ File handling allows us to create, read, write, and delete


files.

✓ File handling in python means working with files to store


read or update data –just like how we use notebooks in
real life
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.
• Store data permanently
• Read large data
• Easy data sharing
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.
Real time examples
• Students attendance register
• Writing attendance –write()
• Checking attendance –read()
• Adding new student-append()
Types of files

• Text files (.txt)


• Binary files (.bin, .jpg, etc.)
DIFFERENCES BETWEEN TEXT FILE AND BINARY FILE

Translators are required No Translators required

Easy to understand because of human readable Difficult to understand because of non


characters human readable characters

Text files will have extensions .txt,.py,.csv Binary files stored in extension .dat,.jpg
Basic file operation in python
• Open a file
• Read a file
• Write a file
• Append data
• Close file
File Modes
• r - Read
• w - Write
• a - Append
OPENING AND CLOSING A TEXT FILE

Operations on files includes creating and opening file writing data in a


file ,traversing a file ,reading data from a file etc…
Python has IO module that contains different functions for handling
files
OPENING A FILE
OPENING A FILE:To open a file in Python, we use the open() function.
The syntax of open() is as follows:
file_object= open(file_name, access_mode)

This function returns a file object called as file handler which is stored in the variable
file_object.
The file_object establishes a link between the program and the data file stored in the
permanent storage.
<[Link]> :returns the access mode in which the file was opened.
<[Link]>:returns the name of the file[path to file]
File Access Modes
CLOSING FILE:

✓Once we are done with the read/write operations on a file, it is a good


practice to close the file.

✓Python provides a close() method to do so. While closing a file, the system
frees the memory allocated to it.

The syntax of close() is:


file_object.close()

Here, file_object is the object that was returned while opening the file.
Opening a file using with clause
In Python, we can also open a file using with clause.
The syntax of with clause is:
with open (file_name, access_mode) as file_object

Example:
with open(“[Link]”,”w”) as myObject:
[Link](“hi hello”)

with open("[Link]","r") as myObject:


content = [Link]()
The advantage of using with clause is that any file that is opened
using this clause is closed automatically, once the control comes
outside the with clause.
reading and writing without with clause reading and writing with with clause

#writing a file without with clause #writing a file using with clause

myobject=open(“[Link]","w") with open("[Link]","w") as myObject:


[Link]("hello students how are you") [Link]("hello students how are
[Link]() you")

#reading a file without "with" clause #reading a file with "with" clause

myobject=open(“[Link]","r") with open("[Link]","r") as myObject:


content=[Link]() content = [Link]()
print(content) print(content)
[Link]()
WRITING TO A TEXT FILE
✓For writing to a file, we first need to open it in write or append mode.
✓If we open an existing file:
➢In write mode, the previous data will be erased, and the file object will be
positioned at the beginning of the file.
➢ In append mode, new data will be added at the end of the previous data as
the file object is at the end of the file.

We use following methods to write data in the file.


• write() - for writing a single string
• writelines() - for writing a sequence of string
The write() method:

✓write() method :for writing a single string

✓write() method :takes a string as an argument and writes it to the text file.

✓It returns the number of characters being written on single execution of the write() method.

✓newline character (\n) at the end should be included of every sentence to mark the end of line.

Consider the following piece of code:


>>> myobject=open("[Link]",'w')
>>> [Link]("Hey I have started #using files in Python\n")
41
>>> [Link]()

On execution, write() returns the number of characters written on to the file.


✓If numeric data are to be written to a text file, the data need
to be converted into string before writing to the file.

For Example:
>>>myobject=open("[Link]",'w’)
>>> marks=58 #number 58 is converted to a string using
#str()
>>> [Link](str(marks))
2
>>>my [Link]()
The writelines() method
✓This method is used to write multiple strings to a file.
✓Takes an iterable object like lists, tuple containing strings as input to
writelines()
✓The writelines() method does not return the number of characters
written in the file.
EXAMPLE:
>>> f=open("[Link]",'w')
>>> lines = ["Hello everyone\n", "Writing multiline strings\n", "This
is the third line"]
>>> f. writelines(lines)
>>>[Link]()
READING FROM A TEXT FILE
Read the contents of a file

There are three ways to read the contents of a file


1. The read() method
2. The readline([n]) method
3. The readlines() method
[Link] read() method:

This method is used to read a specified number of bytes of data


from a data file.

The syntax of read() method is:


file_object.read(n)
Consider the following set of statements to understand the usage
of read() method:
>>>myobject=open("[Link]",'r')
>>> [Link](10)
'Hello ever'
>>> [Link]()
• If no argument or a negative number is specified in read(), the entire file content
is read.

For example,
>>> myobject=open("[Link]",'r')
>>> print([Link]())
Hello everyone
Writing multiline strings
This is the third line
>>> [Link]()
[Link] readline([n]) method:
➢ This method reads one complete line from a file where each line
terminates with a newline (\n) character.
➢ It can also be used to read a specified number (n) of bytes of data from a
file but maximum up to the newline character (\n).

>>> myobject=open("[Link]",'r')
>>> [Link](10)
'Hello ever'
>>> [Link]()

✓ If no argument or a negative number is specified, it reads a complete


line and returns string.
>>>myobject=open("[Link]",'r')
>>> print ([Link]())
'Hello everyone\n'
[Link] readlines() method
The method reads all the lines and returns the lines
along with newline as a list of strings.

>>> myobject=open("[Link]", 'r')


>>> print([Link]())

['Hello everyone\n', 'Writing multiline


strings\n', 'This is the third line']
>>> [Link]()
split() :Function is to display each word of a line separately as an element of a list.

Example:
>>> myobject=open("[Link]",'r')
>>> d=[Link]()
>>> for line in d:
words=[Link]()
print(words)

Output:
['Hello', 'everyone']
['Writing', 'multiline', 'strings']
['This', 'is', 'the', 'third', 'line']
splitlines() is used to return each line as element of a list.

>>> for line in d:


words=[Link]()
print(words)

Output:
['Hello everyone']
['Writing multiline strings']
['This is the third line']
DIFFERENCE BETWEEN:
write() writelines()
1. write() method is used for writing a single 1. writelines() method is used to write multiple
string strings to a file.

2. write() method takes a string as an argument [Link]() Takes an iterable object like lists,
tuple as argument
3. It returns the number of characters being
written on single execution of the write() [Link] writelines() method does not return the
method. number of characters written in the file

Readline() Readlines()

1. This method reads one complete line from a file 1. The method reads all the lines and returns the
lines along with newline as a list of strings.
2. Return data is string type
2. Return data is list type
READING AND WRITING INTO THE FILE:
fobject=open("[Link]","w")
sentence=input("Enter the contents to be written in the file: ")
[Link](sentence)
[Link]()

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


fobject=open("[Link]","r")
a=[Link]()
print(a)
[Link]()

Output:
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]
SETTING OFFSETS IN A FILE
In Python, to access data in a random (non-sequential) fashion, we can use
the following functions:

[Link]() 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])


Where:
• 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.
Program: Application of seek() and tell()
# Open file in read-write mode
file = open("[Link]", "r+")

# Read and display contents


print("Contents:", [Link]())

# Show initial position Output (Example):


print("Initial Position:", [Link]()) Contents: roll_numbers = [1, 2, 3, 4, 5, 6]
Initial Position: 33
# Move to the beginning Position after reset: 0
[Link](0) Position at 10th byte: 10
print("Position after reset:", [Link]()) Remaining Data: rs = [1, 2, 3, 4, 5, 6]

# Move to 10th byte


[Link](10)
print("Position at 10th byte:", [Link]())

# Read remaining data


print("Remaining Data:", [Link]())

# Close file
[Link]()
Creating and traversing a text file:
[Link] 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 [Link] and write data.
fileobject = open("[Link]", "w+")
while True:
data = input("Enter data to save in the text file: ")
[Link](data)
ans = input("Do you wish to enter more data? (y/n): ")
if ans == 'n':
break
Program Output:
[Link]() RESTART: Path_to_file\[Link]
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
[Link] a file and displaying data:
The file will be opened in read mode and reading will begin from the beginning
of the file.
To display data from a text file
fileobject=open("[Link]", "r")
str = [Link]() Explanation of the Program:
1. readline() reads one line at a time from the text file
while str: within the while loop.
2. The lines are displayed using print().
print(str) 3. Once the end of the file is reached, readline() returns an
empty string, causing the loop to stop.
str=[Link]() 4. The file is then closed using close().
[Link]()
Output :
>>> I am interested to learn about Computer SciencePython is easy to learn
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("[Link]", "w+")
[Link]("I am a student of class XII\n")
[Link]("my school contact number is 4390xxx8\n")
[Link](0) # Move file object to the beginning
print([Link]()) # Read and display the content
[Link]()
Output:
I am a student of class XII
my school contact number is 4390xxx8
Explanation of Code:
• The file [Link] 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().
THE PICKLE MODULE:
The Pickle module in Python is used for serializing and deserializing Python
objects.
Convert python objects into a bytes stream (store in file) and convert back to
original object.
Save and load python data

➢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.
Why
• Normally data is lost when the program ends
• Using pickle we can store data permanently in a file
• Real time example:
• Saving students records
• Storing game process
• Saving setting on app
• Machine learning model storage
Methods in Pickle module:

1. dump() method(used to store data into file): Used for serializing (pickling) and
writing Python objects into a binary file. The file which the data are to be
dumped,needs to be opened in binary write mode(wb).
Syntax: dump(data_object, file_object)

Example:
import pickle
listvalues = [1, "Geetika", 'F', 26]
fileobject = open("[Link]", "wb")
[Link](listvalues, fileobject)
[Link]()
[Link]() method(used to read data from file): Used for deserializing (unpickling) and reading Python
objects from a binary file. The file to be loaded is opened in binary read(rb) mode.

Syntax: store_object = [Link](file_object)

Example:
import pickle
print("The data that were stored in file are: ")
fileobject = open("[Link]", "rb")
objectvar = [Link](fileobject)
[Link]()
print(objectvar)

Output :
The data that were stored in file are:
[1, 'Geetika', 'F', 26]
File handling using pickle module
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
bfile=open("[Link]", "ab")
recno=1
while True:
eno = int(input("Employee number: "))
ename = input("Employee Name: ")
salary = int(input("Salary: "))
[Link]([eno, ename, salary], bfile)
recno=recno+1
if input("Add more records (y/n)? ").lower() == 'n':
break
2) Reading Employee Records (Unpickling):
import pickle
with open("[Link]", "rb") as bfile:
try:
while True:
print([Link](bfile))
except EOFError:
pass
Explanation:
• The dump() method stores the employee details as a list in the binary file
[Link].
• 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]
THE END

You might also like