Professional Documents
Culture Documents
A UNIT OF MEET
COMPUTER SCIENCE
BY AVLOKAN MOHAN
[MASTER OF COMPUTER APPLICATIONS]
BY AVLOKAN MOHAN #TEXT FILE HANDLING IN PYTHON
(MASTER OF COMPUTER APPLICATIONS)
INSPIREWEBSOFT CBSE-XII
(COMPUTER SCIENCE)
A UNIT OF MEET (AN ISO 9001:2015 CERTIFIED)
www.inspirewebsoft.com
TEXT FILE
It consists of sequence of lines.
A line is a sequence of characters (ASCII or UNCODE), stored on permanent storage media.
Each line is terminated by a special character, known as EOL(End of Line), by default(‘\n’)
These files can be text file with extension .txt
It stores data in the form of text i.e. human readable form.
FILE MODES
The following modes can be used to work with the text files:-
Modes Description
r It is used for reading only a file.
It is the default mode.
If file does not exist FileNotFoundError
File pointer is placed at the beginning of the file.
w It is used for writing only into a file.
If file does not exist, it creates a new file.
If file exists, then overwrites it.
a It is used for appending or writing into an existing file at the end.
If file does not exist, it creates a new file.
File pointer is at the end of the file if the file exists.
r+ It is used for reading or writing both.
File pointer will be at the beginning of the file.
w+ It is used for reading or writing both.
If file does not exist, it creates a new file.
If file exists, then overwrites it.
File pointer will be at the beginning of the file.
a+ It is used for reading or writing both.
File pointer will be at the end of the file.
If file does not exist, it creates a new file.
Providing file_name
1. Relative Path :- This is the path of the current folder where the file name is specified by default.
Example :- FileObject = open(“inspirewebsoft.txt”, “w”)
2. Absolute Path :- This is the path where the whole path is specified for creating and storing the file.
Example :- FileObject = open(“E:/Desktop/Documents/inspirewebsoft.txt”, “w”)
No Error
with STATEMENT
Instead of using open() or file() for creation 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 that all the resources allocated to the file objects get deallocated automatically once we stop using the
file.
We do not need to close the file explicitly using with statement.
syntax
with open(“<file_name>”, “<mode>”) as file_object:
file manipulation statements