Chapter 2 - File Handling in Python
Chapter 2 - File Handling in Python
• A file is a named location on a secondary storage media like hard disk, pen drive
where data are permanently stored for later access.
• Each program is stored on the secondary device as a file.
• Without files, the output is stored temporarily in RAM. If a new program is run,
previous program goes out of RAM. Thus, storage in files allows us to store and retrieve
the data according to requirements of the programmer.
2. Types of Files
There are mainly two types of data files text file and binary file
A text file consists of human readable characters, which can be opened by any text editor
Binary files are made up of non-human readable characters and symbols, which require specific
programs to access its contents
a. Text File:
A text file can be understood as a sequence of characters consisting of alphabets,
numbers and other special symbols.
Files with extensions like .txt, .py, .csv, etc. are some examples of text files.
Content in the file are stored in sequence of bytes consisting of O’s and 1’s that represent
ASCII value of characters.
So, while opening a text file, the text editor translates each ASCII value and shows us
the equivalent character.
For example, the ASCII value 65 will be displayed by a text editor as letter 'A'.
Each line of text file is terminated by EOL(End of line) character.
After writing a new line and enter key is pressed, a newline character is added.
Example: A file containing Hi and Bye in separate lines stores ASCII values of H, i, \n,
B, y and followed by e.
b. Binary File:
The type of files which stores information in the same format as it is held in memory.
Stores information in stream of bytes which does not represent the ASCII values of
characters
Stores data such as image, audio, video, compressed versions of other files, executable
files, etc. These files are not human readable. Thus, trying to open a binary file using a
text editor will show some garbage values.
Even a single bit change can corrupt the file and make it unreadable to the supporting
application
3. Basic Operations on a File
The basic operations on a file are:
o Reading data from file: The process of extracting already existing data from external
file and displaying through python program.
o Writing data onto file: The process of inserting new data onto a blank external file or
already existing file.
o Appending data onto file: If new data is added to a file which already contains some
data, it is called appending.
File Modes: It specifies the type of operation performed after opening the file. Ex: read, write
etc
Path: It is defined as sequence of directory names which gives the hierarchy to access a
particular file. It is of two types:
i) Absolute Path: If location of file is specified from root directory.
Ex: C:\\Users\\Desktop\\Demo\\[Link]
ii) Relative Path: If location of file is specified from current working directory. No need to
give full path
Ex: if cwd is C:\\Users\\Desktop. Then relative path to text file is [Link]
4. Opening and Closing a Text File
Opening a Text File:
• Files are opened using the open() function which returns a file object.
• File object is defined as a reference to a file on disk. It serves as a connection link
between the programs and file.
Syntax:
file_object = open("filename", "filemode")
Examples: f = open("[Link]") opens the file in read mode.
File pointer is at the beginning. Optional to specify 'r' mode
f = open("[Link]", "w") opens file in write only mode.
Program:
f = open(r"C:\Users\amogh\OneDrive\Desktop\[Link]","w")
print("File name = ", [Link])
print("Closed or not = ", [Link])
print("Opening mode ", [Link])
Output:
File name [Link]
Closed or not False
Opening mode w
Ways of Opening File:
Using double slash :
Ex: x = open("C:\\Demo\\[Link]")
Using raw path:
Ex: x = open(r"C:\Demo\[Link]")
File Attributes:
• [Link]() # True if file is closed
• [Link]() # Access mode of file
• [Link]() # Name of the file
File Open modes
Text file Mode Binary file mode Description Notes
r rb Read only File must already
exist. otherwise
IOError is raised,
Default mode
w wb Write only If file doesn’t exist,
it is created. If it
exists, python
truncates existing
data and overwrites
a ab Append If file doesn’t exist,
it is created. If it
exists. Current data
is retained and new
data is appended to
end of file
r+ rb+ Read and Write File must be exist.
Reading and then
writing taken place.
Existing data not
vanished
w+ wb+ Write and Read File is created if
doesn’t exist. If it
exists, it overwrites
existing data. First
write, then reading
a+ ab+ Append and Read If file doesn’t exist,
it is created. If file
exists, current data is
retained & new data
is appended to end
of the file
1. write() method:
✓ This function is used to insert single string as an arguments.
✓ It returns the number of characters being written on single execution.
✓ If data is in different format, it needs to be converted to string using str()
✓ We need to add a newline character(“\n”) to end of the string
Syntax: file [Link](string)
Example: To write a employee’s name in a text file using write() method
f=open(“[Link]”, “w”)
if not f:
print(“file does not created”)
else
for 1 in range (6):
name=input(“enter name of the employee:”)
[Link](name)
[Link]()
Output:
Enter name of employee: Khushi
Enter name of employee: Shreya
Enter name of employee: Ashmit
Enter name of employee: Kiyaan
Enter name of employee: Kiran
Enter name of employee: Rahul
2. writelines() method:
✓ writelines() function is used to write multiple strings to a file in the form object like
lists, tuple, etc.
✓ Unlike write(), the writelines() method does not return the number of characters written
in the file.
Syntax: file_object.writelines(LIST/TUPLE)
Example of writelines():
F=open(r"C:\Users\amogh\OneDrive\Desktop\[Link]","w")
L= ["Hi Everyone\n","I'm learning File Handling"]
[Link] (L)
[Link]()
output:
Hi Everyone
I’m learning File Handling
2. Reading data from Text File:
• Reading data from text file means extracting already existing data from external file
and displaying through python program.
• The necessary condition is that the file must exist. File can be opened in r, r+, w+ and
a+ modes.
The functions for reading data from text file includes:
1. read()
2. readline([n])
3. readlines()
1. read():
✓ This function is used to returns a string containing all characters in an existing file.
✓ Reads file content at once
✓ Used to read specific number of bytes of data from the data file.
✓ If no argument or a negative number is specified in read(), the entire file content is read.
Syntax: [Link](n) Assume we have text file named [Link] with following content
Apple
Banana
Cherry
Example:
With open(“[Link]”, “r”)as file
Content = [Link]()
Print(content)
Output
Apple
Banana
Cherry
2. readline([n]):
This method reads complete file line by line including “\n” character from the file. And can use
with arguments to read a specified number (n) of bytes of data from a file.
Syntax: [Link](n) //n is optional
If no argument or a negative number is specified in readline(), the entire line is read.
Example:
With open(“[Link]”, “r”)as file
Line1 = [Link]()
Line2= [Link]()
Print(“First call:”, Line1)
Print(“Second call:”, Line2)
Output
First call: Apple
Second call: Banana
3. readlines():
This function is used to read all lines from a text file and return the result in the form of
list of string. Each element in list retains its trailing \n character.
Syntax: [Link]()
Example
With open(“[Link]”, “r”)as file
all_lines = [Link]()
print(all_lines)
Output:
[‘Apple\n’, ‘Banana\n’, ‘Cherry\n’]
To access particular data from to file with its offsets (positions) we need to use built-in
functions like seek() and tell()
This function returns an integer that specifies the current position of the file object in the file.
(file pointer)
Syntax: File_object.tell()
This function is used take the file pointer to a specified position from reference point.
Syntax:
reference point- this is starting point, from which offset has to start.
It can be
2-End of file.
Example:
b = open (“[Link]”, “r+”)
str = [Link]()
print(str)
print(“Initially, the position of the file object is:”, [Link]())
[Link](0)
print(“now the file object is at the beginning of the file:”, [Link]())
[Link](10)
print(“moving to 10th byte position from the beginning of file”)
print (“the position of the file object is at”, [Link]())
str=[Link]()
print(str)
Output
Roll_number = [1, 2, 3, 4, 5, 6]
Initially the position of the file object is: 30
Now the file object is at beginning of the file: 0
moving to 10th byte position from the beginning of file
The position of the file object is at 10
rs = [1, 2, 3, 4, 5, 6]
Output:
Writing data in file
Pickle module deals with the binary file to dump and load binary data. Dumping the data is
serialization (pickling) and loading the data is De-serialization (unpickling).
Pickling(serialization): It is the process of converting python objects into bytestream.
(writing)
Unpickling (De-serialization): The process of converting bytestream back to python object
(Reading)
This method is used to convert (pickling) python objects for writing data in binary file (.dat
file). The file in which data to be dumped should open with binary write mode (wb).
Syntax:
Example
import pickle
listvalues = [1, ‘Geetika’, ‘f’, 26]
X=open (“[Link]”, “wb”)
[Link] (listvalues.X)
[Link]()
This method is used to load (unpickling) data from the binary file. The file to be loaded
should be opened in binary read mode (rb).
Syntax:
Example:
import pickle
print(“the data that were stored in file are:”)
X=open (“[Link]”, “wb”)
Store = [Link] (X)
[Link]()
Print(store)
Output:
The data that were stored in file are:
[1, ‘Geetika’, ‘F’, 26]