File Handling
File Handling
Opening a file
It is done using the open() function. No module is required to be imported for this function.
• The file should exist in the same directory as the python program file else, full address of the file
should be written on place of filename.
Closing a file
close() function closes the file and frees the memory space acquired by that file. It is used at
the time when the file is no longer needed or if it is to be opened in a different file mode.
Writing to a file
There are two ways to write in a file.
1. write() : Inserts the string str1 in a single line in the text file.
readline() : Reads a line of the file and returns in form of a string. For specified n, reads
at most n bytes. However, does not reads more than one line, even if n exceeds the
length of the line.
readlines() : Reads all the lines and return them as each line a string element in a list.
pickle.load()