4.0 Notes of File Handling
4.0 Notes of File Handling
A file is a document or the data stored on a permanent storage device which can be read, written or
rewritten according to requirement.
Note: All the files are assigned a name that is used for identification purposes by the operating system
and the user.
Note: Data maintained inside the files is termed as persistent data means permanent in nature.
1. Opening a file
2. Processing Data like read, write etc
3. Closing the file
Creating a file
Inserting data in a file
Appending data in a file
Traversing a file for displaying data on screen
Deleting data from a file
Updating data in a file
Creating a copy of a file
Convert the data file from one type to another
1. Text File: A text file is a sequence of lines. A line is a sequence of characters (ASCII) stored
on permanent storage. Each line is terminated by a special character known as END OF LINE
(EOL). By default EOL character is newline character (‘\n’). Extension of text file is (.txt).
2. Binary File: Binary files are used to store binary data such as images, video files, audio files etc.
There is no delimiter for a line. Extension of binary file is (.dat).
Note: Binary files are easier, faster and secured than text files for reading and writing operation on data.
Opening a File
We can open file by using open() or file() function. It takes two argument first argument indicates file
name with extension and second argument indicates mode of accessing the file.
Ex: F1 = open(‘abc.txt’, ’r’) #Text file is open in read mode with object F1
with statement
Apart from using open() or file() function for creating of file with statement can also be used for the same
purpose. We can use this statement to group file operation statements within block. Using with ensures
1
that all the resources allocated to the file objects get deallocated automatically once we stop using the file.
So, we are not required to close the file.
File Modes
The file mode defines how the file will be accessed. A mode either read (‘r’), write (‘w’) or append (‘a’).
Note: The default file open mode is read mode (‘r’), if we do not provide any file open mode. Python
will open it in read mode (‘r’)
Closing a File
We can close a file by using close() function. Python automatically closes a file when the reference object
of a file is reassigned to another file. But it is good practice to use the close() function to close a file.
Syntax: FileObject.close()
Note: After closing a file no tasks can be performed on that file through the file object.
2
Writing to Text File
1. write(string): This function takes a string as parameter and write it in the specified file.
We will have to add ‘\n’ character to the end of the string. In order to write numeric value we have
to convert it to string.
Syntax: FileObject.write(string)
F = open(‘names.txt’, ‘w’)
F.close()
Note: In the above program data present in the file shall be overwritten every time we run the program.
In order to avoid this we should use append mode (‘a’).
Append means ‘to add to’. So if we want to add more data to a file which already has some data in it.
Open for writing and if it exists then append data to the end of the file.
Ex: WAP to append your last name in the already existing text file names.txt.
F = open(‘names.txt’, ‘a’)
F.write(‘ Gupta’)
F.close()
2. writelines(sequence): This function is used to write sequence data like list or tuple which
include strings. This function does not add any EOL character to the end of string. So, we have to
do it ourselves.
Syntax: FileObject.writelines(sequence)
Ex: WAP to write a list data which contain name of students in the file stunames.txt.
F = open(‘stunames.txt’, ‘a’)
L=[‘Amit’,’Rahul’,’Karan’,’Sumit’]
F.writelines(L)
F.close()
Note: While reading from or writing to the file, the cursor always starts from the beginning of the file.
Ex: WAP to read and display whole data present in the text file names.txt.
f = open(‘names.txt’, ‘r’)
x = f.read()
print(x)
f.close()
2. read(n): This function is used to read n number of characters from the file. If file contain
less than n characters then it will read until the end of the file.
Ex: WAP to read and display first four characters from the text file names.txt.
f = open(‘names.txt’, ‘r’)
x = f.read(4)
print(x)
f.close()
3. readline(): This function is used to read only one line from the file starts from first line. It
reads first line in first execution, second line in second execution and so on.
Ex: WAP to read and display first two lines from the text file names.txt.
f=open(‘names.txt’, ‘r’)
L1 = f.readline()
L2 = f.readline()
f.close()
4. readlines(): This function is used to read all lines from the file and return a list of lines and each
line contain ‘\n’ as EOL character.
Ex: WAP to read and display data present in the text file names.txt.
4
f = open(‘name.txt’, ‘r’)
L = f.readlines()
for x in L:
print(x)
f.close()
Pickling: It refers to the process of converting the structure to a byte stream before writing to the
file.
Unpickling: It refers to the process of converting the byte stream back to the original structure.
Note: In order to do the process of pickling or unpickling we need to import a module ‘pickle’. It
provide two main functions dump() and load().
dump() function is used for creation of a binary and to write object in the file, which is open in binary
access mode. By using dump() function we can write any kind of data such as list, tuple, dictionary etc.
Ex: WAP to create a binary file marks.dat and write data present in the list which contain marks of
five subjects.
import pickle
F = open(‘marks.dat’, ‘wb’)
pickle.dump(L,F)
F.close()
Note: In the above program data present in the file shall be overwritten every time we run the program.
In order to avoid this we should use append mode (‘ab’).
Append means ‘to add to’. So if we want to add more data to a file which already has some data in it.
Open for writing and if it exists then append data to the end of the file.
Ex: WAP to create a binary file marks.dat and append data present in the list which contain marks of
five subjects.
import pickle
F = open(‘marks.dat’, ‘ab’)
5
L = [60, 45, 78, 59, 80]
pickle.dump(L,F)
F.close()
load() function is used to read object from the binary file. Once data is stored using dump() function then
it can be used for reading.
Note: We need to call load() function each time dump() function is called.
Ex: WAP to read data from the file marks.dat which contain a list of marks.
import pickle
F = open(‘marks.dat’, ‘rb’)
L = pickle.load(F)
print(L)
F.close()
Ex: WAP to read all data from the file marks.dat which contain lists of marks.
import pickle
F = open(‘marks.dat’, ‘rb’)
try :
while True :
L = pickle.load(F)
print(L)
except :
pass
finally:
F.close()
6
Relative and Absolute Path
Files are organized into directories also called folders. Every running program has a current directory
which is the default directory for most operations.
A string like cwd (Current Working Directory) that identifies a file is called a path. Path is a sequence of
directory names which give you the hierarchy to access a particular directory or file name.
A relative path starts from the current directory whereas an absolute path starts from the topmost
directory in the file system.
7
Python Try Except
The try block lets you test a block of code for errors.
The except block lets you handle the error.
The finally block lets you execute code, regardless of the result of the try and except blocks.
Exception Handling
When an error occurs as we call it exception, Python will normally stop and generate an error message. These exceptions can
be handled using the try statement:
Example: The try block will generate an exception, because x is not defined:
try:
print(x)
except:
print("An exception occurred")
Since the try block raises an error, except block will be executed. Without the try block, the program will crash and
raise an error:
Example: This statement will raise an error, because x is not defined:
print(x)
Many Exceptions
We can define as many exception blocks as we want, e.g. if you want to execute a special block of code for a special kind of
error:
Example: Print one message if the try block raises a NameError and another for other errors:
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
Else
We can use the else keyword to define a block of code to be executed if no errors were raised:
Example: In this example, the try block does not generate any error:
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
Finally
The finally block, if specified, will be executed regardless if the try block raises an error or not.
Example:
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
This can be useful to close objects and clean up resources.
Example: Try to open and write to a file that is not writable:
try:
f = open("demofile.txt")
f.write("Lorum Ipsum")
except:
print("Something went wrong when writing to the file")
finally:
f.close()
The program can continue, without leaving the file object open.