Home »
Python
File Handling in Python
Python file handling: In this tutorial, we are going to learn about the file handling in python programming language with examples.
Submitted by Sapna Deraje Radhakrishna, on October 13, 2019
Python file handling
File handling is very important and error-prone in any web application. It is quite easy to have a resource leakage with files if the file reading or writing is not gracefully closed.
In python, the concept of file handling is rather easy and short. The file operation takes place in below-mentioned order:
- Open a file if a predefined or an optional mode
- Read or write
- Close the file
Open a file
The open() function in python, opens a file in read, write or append mode. The open() will return a file object.
Syntax:
open(filename, mode)
There are various types of mode,
Mode | Description |
'r' | Open for reading ( default mode) |
'w' | Open for writing |
'a' | Open for appending |
'r+' | Open for both read and write |
't' | Open the file in text mode |
'b' | Open the file in binary mode |
Reading a file
# importing the module
import os
# function to read file content
def read_file(file_loc):
file_obj = open(file_loc)
print(file_obj.read())
# main function/code
if __name__ == '__main__':
dir_name = os.path.dirname(__file__)
file_name = os.path.join(dir_name, 'samples/sample_file.txt')
read_file(file_name)
Output
this is a sample file
In the above example, if the mode is not passed as an argument, then the file is opened with "read" mode.
Another way to read a file is to invoke only required number of characters.
# importing the module
import os
# function to read file content
def read_file(file_loc):
file_obj = open(file_loc)
print(file_obj.read(10))
# main function/code
if __name__ == '__main__':
dir_name = os.path.dirname(__file__)
file_name = os.path.join(dir_name, 'samples/sample_file.txt')
read_file(file_name)
Output
this is a
To read the lines of the file as a list, use the function readlines(), returns a list of lines in the entire file. The reading methods return empty values when the EOF is reached.
# importing the module
import os
# function to read file content
def read_file(file_loc):
file_obj = open(file_loc)
print(file_obj.readlines())
# main function/code
if __name__ == '__main__':
dir_name = os.path.dirname(__file__)
file_name = os.path.join(dir_name, 'samples/sample_file.txt')
read_file(file_name)
Output
['this is a sample file']
Writing to a file
# importing the module
import os
# function to read file content
def read_file(file_loc):
file_obj = open(file_loc)
print(file_obj.read())
#print(file_obj.read(10))
# function to write to the file
def write_file(file_loc):
file_obj = open(file_loc, "w")
file_obj.write("MY sample file for include_help\n")
file_obj.write("I can write long long lines")
file_obj.close()
# main function/code
if __name__ == '__main__':
dir_name = os.path.dirname(__file__)
write_file_name = os.path.join(dir_name, 'samples/sample_file_1.txt')
write_file(write_file_name)
read_file(write_file_name)
In the above example, we see the method close(), it is very important that the file object which is opened to write is always closed in order to terminate the resources in use and frees the system.
Append Mode
# importing the module
import os
# function to read file content
def read_file(file_loc):
file_obj = open(file_loc)
print(file_obj.read())
# function to write to the file
def write_file(file_loc):
file_obj = open(file_loc, "w")
file_obj.write("MY sample file for include_help\n")
file_obj.write("I can write long long lines")
file_obj.close()
# appending the file
def append_file(file_loc):
file_obj = open(file_loc, "a")
file_obj.write("\n appending the information")
file_obj.close()
# main function/code
if __name__ == '__main__':
dir_name = os.path.dirname(__file__)
write_file_name = os.path.join(dir_name, 'samples/sample_file_1.txt')
write_file(write_file_name)
append_file(write_file_name)
read_file(write_file_name)
Output
MY sample file for include_help
I can write long long lines
appending the information
The append mode is used in case of appending the file with additional information, and not to create the file at every invocation.
with() method
with() method is a useful method which closes all the file opened in any mode, automatically and also done the auto cleanup.
# importing the module
import os
# function for read operation
def with_read_operation(file_loc):
with open(file_loc) as file_obj:
data = file_obj.read()
print(data)
# function for write operation
def with_write_operation(file_loc):
with open(file_loc, "w") as file_obj:
file_obj.write("writing using with()")
# main function/code
if __name__ == '__main__':
dir_name = os.path.dirname(__file__)
write_file_name = os.path.join(dir_name, 'samples/sample_file_2.txt')
with_write_operation(write_file_name)
with_read_operation(write_file_name)
Output
writing using with()
Other file operations are
Method | Description |
tell() |
Returns an integer giving the file objects current position in the file represented as number of bytes from the beginning of the file. |
seek(offset, whence) |
Changes the file object position. The position is computed from adding the offset to a ref point, and the ref point is selected from the whence argument. |