0% found this document useful (0 votes)
8 views15 pages

2 File Handling in Python Notes

Chapter 2 of the Computer Science syllabus focuses on file handling in Python, detailing the importance of files for permanent data storage and the types of files, including text and binary files. It explains how to open, close, read, and write to files using various methods and access modes, as well as the use of the 'with' clause for automatic file closure. Additionally, it covers methods for navigating within files, such as seek() and tell(), and provides examples of creating and manipulating text files.

Uploaded by

diganthhh1
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)
8 views15 pages

2 File Handling in Python Notes

Chapter 2 of the Computer Science syllabus focuses on file handling in Python, detailing the importance of files for permanent data storage and the types of files, including text and binary files. It explains how to open, close, read, and write to files using various methods and access modes, as well as the use of the 'with' clause for automatic file closure. Additionally, it covers methods for navigating within files, such as seek() and tell(), and provides examples of creating and manipulating text files.

Uploaded by

diganthhh1
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

II PUC 2025-26 (New syllabus) Computer Science Chapter 2 File handling in python

Chapter 2 File handling in Python


Introduction to Files
 Programs written in Python accept the input, manipulate it and display the output.
 Input is entered through keyboard and output is displayed on the monitor.
 The output is available only during execution of the program.
 Output is displayed temporarily, because the variables used in a program have a lifetime till the program is under execution.
 To store entered input and generated output permanently for later use, secondary storage devices are used.
 Each python program is stored on the secondary storage device as a file with .py extension.
 Like this, the data, entered input, and the output can be stored permanently into a file on secondary storage devices.

File: A file is a named location on a secondary storage device where data are permanently stored for later access.

Types of Files
 Computers store every file as a collection of 0s and 1s i.e., in binary form.
 Every file is just a series of bytes stored one after the other.

There are mainly two types of data files based on the content
1) Text file
2) Binary file.
Text file
 A text file is a sequence of characters consisting of alphabets, numbers and other special symbols.
 A text file consists of human readable characters, which can be opened by any text editor.
 ASCII, UNICODE or any other encoding schemes are used to store each character of the text file as bytes.
 Files with extensions like .txt, .py, .csv, etc. are some examples of text files.
 A .docx file contains many additional information like the author's name, page settings, font type and size, date of creation and
modification, etc.
 A text file includes several lines of text, but in computer memory, these contents are stored in sequence of bytes consisting of 0s and
1s.
 A special character, called the End of Line (EOL), terminates each line of a text file.
 The default EOL character in Python is the newline (\n).
 Contents in a text file are usually separated by whitespace, but comma (,) and tab (\t) are also used.
 When a text file is opened, the text editor translates each ASCII value to equivalent human readable character.
 For example, the ASCII value 65 (binary equivalent 1000001) will be displayed by a text editor as the letter ‘A’.
Dept. Of Computer Science, Sri Adichunchanagiri Ind PU college, Shivamogga 1
II PUC 2025-26 (New syllabus) Computer Science Chapter 2 File handling in python

Binary Files
 These are files, which are made up of non-human readable characters and symbols and require specific software to access its
contents.
 Binary files are stored in terms of bytes (0s and 1s), but, these bytes do not represent the ASCII values of characters.
 Binary file represents the actual content such as image, audio, video, compressed versions of other files, executable files, etc.
 As binary files are not human readable, trying to open a binary file using a text editor will show some garbage values.
 A single bit change in binary file can corrupt the file and make it unreadable.
 It is difficult to remove any error in the binary file as the stored contents are not human readable.

Opening and Closing a Text File


 Python has the io (input and output) module that contains different functions for handling files.
 Operations on files include creating and opening a file, writing data in a file, traversing a file, reading data from a file and so on.
Opening a file
open() function is used to open a file in python.

Syntax: file_object= open(file_name, access_mode)


Here,
 file_object is a variable which stores file handle.
 The file_name is the name of the file that has to be opened.
 The access_mode represents the mode in which the file has to be accessed by the program. It is an optional argument.

Example: myObject=open(“[Link]”, “r”) ------------opens file in read mode only

File opening Syntax: file_object= open(file_name, access_mode)

file_object:
 file_object is a variable which stores file handle.
 This variable is used for read and write operations by calling the functions defined in the Python’s io module.
 The file_object establishes a link between the program and the data file stored in the permanent storage.
 If the file does not exist, the above statement creates a new empty file with mentioned name.
Attributes of file_object: Attributes of file_object tells basic information about the file, such as:
a) <[Link]>: returns true if the file is closed and false otherwise.
b) <[Link]>: returns the access mode in which the file was opened.

Dept. Of Computer Science, Sri Adichunchanagiri Ind PU college, Shivamogga 2


II PUC 2025-26 (New syllabus) Computer Science Chapter 2 File handling in python

c)<[Link]>: returns the name of the file.


file_name
 It is the name of the file that has to be opened.
 If the file is not in the current working directory, then specify the complete path of the file along with its name.

access_mode
 It represents the mode in which the file has to be accessed by the program. It is an optional argument.
 It is also referred as processing mode. Here mode means the operation for which the file has to be opened.
 The default mode is the read mode.
 By default, files are opened in text mode that means strings can be read or written.
 Files containing non-textual data are opened in binary mode that means read/write operations are performed in terms of bytes.

Following is the list of various file access modes


The file offset position refers to the position of the file object when the file is opened in a particular mode.

File mode Description File offset position


<r> Opens the file in read-only mode. Beginning of the file
<rb> Opens the file in binary and read-only mode. Beginning of the file
<r+> or <+r> Opens the file in both read and write mode. Beginning of the file
<w> Opens the file in write mode. If the file already exists, all the contents will be Beginning of the file
overwritten. If the file does not exist, then a new file will be created.
<wb+> or <+wb> Opens the file in read, write and binary mode. If the file already exists, the Beginning of the file
contents will be overwritten. If the file does not exist, then a new file will be
created.
<a> Opens the file in append mode. If the file does not exist, then a new file will be End of the file
created.
<a+> or <+a> Opens the file in append and read mode. If the file does not exist, then it will End of the file
create a new file.

Closing a file
 A file should be closed as soon as all operations on it are completed.
 While closing a file, the system frees the memory allocated to it.
 Close ( ) function is used to close a file.
Dept. Of Computer Science, Sri Adichunchanagiri Ind PU college, Shivamogga 3
II PUC 2025-26 (New syllabus) Computer Science Chapter 2 File handling in python

 Python makes sure that any unwritten or unsaved data is flushed off (written) to the file before it is closed.
 If the file object is re-assigned to some other file, the previous file is automatically closed.

Syntax: file_object.close();
Here,
file_object is the object that was returned while opening the file.

Example:
myObject=open(“[Link]”, “r”);
[Link]();

Opening a file using with clause


Syntax: with open (file_name, access_mode) as file_ object:
Example:

Advantage of using with clause


 Any file that is opened using with clause is closed automatically.
 If an exception (error) occurs, then the file is closed automatically.
 It provides a simple syntax.

Writing to a Text File


 For writing to a file, it should be opened in write or append mode.
 If an existing file is opened in write mode, then the previous data will be erased, and the file object will be positioned at the beginning
of the file.
 If an existing file is opened in append mode, new data will be added to the end of the previous data as the file object is at the end of
the file.

Dept. Of Computer Science, Sri Adichunchanagiri Ind PU college, Shivamogga 4


II PUC 2025-26 (New syllabus) Computer Science Chapter 2 File handling in python

Following methods are used to write data in the file.

1) write ( ) - for writing a single string


2) writelines ( ) - for writing a sequence of strings

The write () method


 This method writes only one string to the text file at a time.
 This method returns the number of characters being written to text file.
 User need to add a newline character (\n) at the end of every sentence to mark the end of line.
 If numeric data are to be written to a text file, the data need to be converted into string first.
 This method writes data onto a buffer first. When the file is closed, this data is moved to the file.
 flush ( ) method can also be used to clear the buffer and write contents in buffer to the file.

Example 1: Consider the following piece of code:


>>> myobject=open("[Link]",'w')
>>> [Link]("computer science\n")
17 ------------------ Number of characters written on to the file
>>> [Link]( )

Example 2:
>>>myobject=open ("[Link]",'w')
>>> marks = 58
>>> [Link] (str(marks)) #number 58 is converted to a string using str( )
2
>>>[Link]( )

writelines ( ) method:
 This method is used to write multiple strings to a file.
 User need to pass an iterable object like lists, tuple, etc. containing strings to the writelines ( ) method.
 This method does not return the number of characters written in the file.
Example:
myobject=open("[Link]",'w')

Dept. Of Computer Science, Sri Adichunchanagiri Ind PU college, Shivamogga 5


II PUC 2025-26 (New syllabus) Computer Science Chapter 2 File handling in python

lines = ["computer\n", "science"]


[Link](lines)
[Link]()

Output: As stored in file [Link]


computer
science

Reading from a Text File: A file must be opened in “r”, “r+”, “w+” or “a+” mode for reading.
Following are the three ways to read the contents of a file:
a) The read( ) method
b) The readline([n]) method
c) The readlines( ) method

a) The read() method:

 This method is used to read a specified number of bytes of data from a data file.
 If no argument or a negative number argument is specified, then this method reads entire file.
Syntax: file_object.read(n);

Example 1: reading specified number of characters


>>>myobject=open("[Link]",'r')
>>> [Link](12)
'computer sci' -------------------only 12 character text from the file ‘[Link]’ are read
>>> [Link]()

Example 2: reading complete text from a file


>>> myobject=open("[Link]",'r')
>>> [Link]()
computer science -------------------complete text from the file ‘[Link]’
>>> [Link]()

Dept. Of Computer Science, Sri Adichunchanagiri Ind PU college, Shivamogga 6


II PUC 2025-26 (New syllabus) Computer Science Chapter 2 File handling in python

b) The readline ([n]) method


 This method reads one complete line which is terminated with a newline (\n) character.
 It also reads a specified number of bytes of data but maximum up to the newline character (\n).
 If no argument or a negative number is specified, it reads a complete line.
 Loops are used to read the entire file line by line using the readline(). This process is known as looping/ iterating over a file object.
 It returns an empty string when EOF is reached.

Example 1: reading complete line till new line character(\n)


>>> myobject=open("[Link]",'r')
[Link]( )
'welcome to\n'
>>> [Link]()

Example 2: reading only specified number of characters


>>> myobject=open("[Link]",'r')
>>> [Link](3)
‘wel’
>>> [Link]()

c) readlines() method
 This method reads all the lines in a file and returns the lines along with newline as a list of strings.
 When a file is read using readlines() method, lines in the file become members of a list, where each list element ends with a newline
character (‘\n’).
 To display each word of a line separately as an element of a list, then use split() function.
 To return each line as element of a list splitlines() method is used.

Example 1: reading all lines from a file


>>>myobject=open("[Link]", 'r')
[Link]()
['welcome to\n', 'python\n', 'programming\n']
>>>[Link]()

Dept. Of Computer Science, Sri Adichunchanagiri Ind PU college, Shivamogga 7


II PUC 2025-26 (New syllabus) Computer Science Chapter 2 File handling in python

Example 2: displaying each word as an element of a list using split () method

Example 3: displaying each line as an element of a list using splitlines () method

Program: A python program to accept a string from the user, write it to a text file, read the content from file and displays it on the screen.

Dept. Of Computer Science, Sri Adichunchanagiri Ind PU college, Shivamogga 8


II PUC 2025-26 (New syllabus) Computer Science Chapter 2 File handling in python

Output:

Setting Offsets in a File


 Read (), write () methods are used to access the data sequentially from a file.
 To access data in a random order, Python gives seek () and tell () methods.
tell () method
 This method returns an integer that specifies the current position of the file object in the file.
 The position specified is the byte position from the beginning of the file.
Syntax: file_object.tell()

Example:
fileobject=open("[Link]","r+")
fileobject. tell ()

seek () method: This method is used to position (move) the file object at a particular position in a file.
Syntax: file_object.seek(offset [, reference_point])

Here,
 offset is the number of bytes by which the file object is to be moved.
 reference_point indicates the position from which the file object is to be moved.
 reference_point can have any of the following values:
0 - beginning of the file
1 - current position of the file
2 - end of file
 By default, the value of reference_point is 0, i.e. the offset is counted from the beginning of the file.

Example: [Link] (5,0)

Here,
th
file object will be placed at 5 byte position from the beginning of the file.

Dept. Of Computer Science, Sri Adichunchanagiri Ind PU college, Shivamogga 9


II PUC 2025-26 (New syllabus) Computer Science Chapter 2 File handling in python

Program: A python program to demonstrates the usage of seek() and tell().

Output:

Creating and traversing a text file


 After learning various methods to open and close a file, read and write data in a text file, find the position of the file object and move
the file object at a desired location, let us now perform some basic operations on a text file.
 To perform these operations, consider a file [Link].

Creating a file and writing data


 To create a text file, use the open() method and provide the filename and the mode.
 If write mode (w) is used , then all the existing contents of file will be lost, and an empty file will be created with the same name.

Dept. Of Computer Science, Sri Adichunchanagiri Ind PU college, Shivamogga 10


II PUC 2025-26 (New syllabus) Computer Science Chapter 2 File handling in python

 But, if the file is created in append mode (a), then the new data will be written after the existing data.
 In both cases, if the file does not exist, then a new empty file will be created.

Program: A python program to create a text file and write data in it

Output:

Traversing a file and displaying data


Program 1: A python program to display all its data by traversing from beginning of file till end of file.

Dept. Of Computer Science, Sri Adichunchanagiri Ind PU college, Shivamogga 11


II PUC 2025-26 (New syllabus) Computer Science Chapter 2 File handling in python

Output:

Performing read and write operations in single program


Since both the operations have to be performed using a single file object, the file will be opened in w+ mode.
Program: To perform read and write operation in single program

Dept. Of Computer Science, Sri Adichunchanagiri Ind PU college, Shivamogga 12


II PUC 2025-26 (New syllabus) Computer Science Chapter 2 File handling in python

Output:

The Pickle Module


 It is module used for serializing and de-serializing any Python object by storing its structure and data in binary file.
 The pickle module deals with binary files. Here, data are not written but dumped and data are not read but loaded.
 The Pickle Module must be imported to load and dump data.
 The pickle module provides two methods dump () and load () to work with binary files.

Pickling or Serialization
 It is the process of transforming data or an object in memory (RAM) to a byte streams in a binary file on a disk or in a database or
sent through a network.
De-serialization or unpickling
 It is the inverse of pickling process where a byte stream is converted back to Python object.

The dump() method


 This method is used to convert (pickling) Python objects for writing data in a binary file.
 The file in which data are to be dumped, needs to be opened in binary write mode (wb).

Dept. Of Computer Science, Sri Adichunchanagiri Ind PU college, Shivamogga 13


II PUC 2025-26 (New syllabus) Computer Science Chapter 2 File handling in python

Syntax: dump (data_object, file_object)


Where
data_object is the object that has to be dumped to the file with the file handle named file_object.

Example: following program writes the record of a student in the binary file [Link] using the dump().
import pickle
listvalues=[1,"Geetika",'F', 26]
fileobject=open("[Link]", "wb")
[Link](listvalues,fileobject)
[Link]()

The load() method


 This method is used to load (unpickling) data from a binary file.
 The file to be loaded is opened in binary read (rb) mode.

Syntax: Store_object = load(file_object)


Here,
The pickled Python object is loaded from the file having a file handle ‘file_object’ and is stored in a new file handle called
‘store_object’.

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

Output:

Dept. Of Computer Science, Sri Adichunchanagiri Ind PU college, Shivamogga 14


II PUC 2025-26 (New syllabus) Computer Science Chapter 2 File handling in python

File handling using pickle module


The following program,
 Accepts a record of an employee from the user and appends it in the binary file ‘[Link]’.
 Thereafter, the records are read from the binary file and displayed on the screen using the same object.
 The user may enter as many records.
 The program also displays the size of binary files before starting with the reading process.

Dept. Of Computer Science, Sri Adichunchanagiri Ind PU college, Shivamogga 15

You might also like