Python File Handling Beginners – Open, Read and Close File Functions
In this post, you’ll learn about Python File Handling Beginners – Open, Read, and Close File Functions with step by step guide.
Table of Contents
What is File Handling?
File Handling refers to operations such as create, append, write, read, and delete related to files irrespective of their extension.
Files are created in the storage disk of the computer. When we open a file and add some contents to it system updates the file
to the respective path.
Where File Handling is used?
While building real-time applications we can use it to store information to file. Such as creating a .txt file else creating an excel file
of course python has a particular module dedicated to creating excel sheets. But under the hood python, built-in functions are used.
Opening a File
Python has built-in functions for file manipulation. A file can be created by the open()
a function which takes certain arguments.
Before we proceed to show you how to open or create a file. It is necessary to learn the mode of access this tells python weather to open the file in write or read mode.
List of Mode of Access
Symbol | Meaning |
---|---|
r | Opens file into read-only mode (a default value) |
w | Opens file in write mode |
x | If give does not exist in a given path than creating it (added in python version 3.3). FileExistsError an exception has occurred if the file already exists in the path. |
a | This is an append mode where contents are added at the end line of the file. |
b | Binary Mode |
t | Text Mode |
+ | This mode opens file can be read as well as written |
Opening file using open()
This function opens the file in the given path and returns its object called file object. The file can be of any given extension.
The File object is a consiste the information related to that file something similar to this <_io.TextIOWrapper name=’file name’ mode=’mode of access’ encoding=’UTF-8′></_io.TextIOWrapper>.
General syntax of open():
open(file_name, mode='mode of access(r, w, a etc)', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
Example
file_res = open('m/test.txt', 'r') print(file_res) print(type(file_res)) file_res.close() #PYTHON OUTPUT <_io.TextIOWrapper name='test.txt' mode='r' encoding='UTF-8'> <class '_io.TextIOWrapper'>
As you can see that if we print files then we can see some of the information related to file name and mode of access.
By type()
the function we can get to know that a file is a class object.
Now we’ll use python built-in dir()
function to see what function we can use.
file_res = open('m/test.txt', 'r') print(dir(file_res)) file_res.close() #PYTHON OUTPUT ['_CHUNK_SIZE', '__class__','__del__', '__delattr__', '__dict__', '__dir__', '__doc__', '__enter__', '__eq__', '__exit__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__iter__', '__le__','__lt__', '__ne__', '__new__', '__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_checkClosed','_checkReadable', '_checkSeekable', '_checkWritable', '_finalizing', 'buffer', 'close', 'closed', 'detach', 'encoding', 'errors', 'fileno', 'flush', 'isatty', 'line_buffering','mode', 'name', 'newlines', 'read', 'readable', 'readline', 'readlines', 'seek', 'seekable', 'tell', 'truncate', 'writable', 'write', 'writelines']
dir()
function in python lists the function available to be used on a particular object.The read()
a function is what we require to read from file.
Reading from file
file_res = open('m/test.txt', 'r') print(file_res.read()) file_res.close() #PYTHON OUTPUT This is a text file
file_res = open('m/test.txt', 'r') print(file_res.read()) #PYTHON OUTPUT This is a text file
The Size
an optional parameter is available if you want to peak at the start of the file. It takes an integer as argument.
file_res = open('m/test.txt', 'r') print(file_res.read(10)) file_res.close() #PYTHON OUTPUT This is a
Example: Reading file contents multiple files
path = 'm/test.txt' file_res = open(path, 'r') print('1) File Contents : {} \n'.format(file_res.read())) file_res.seek(0) print('2) File Contents : {} \n'.format(file_res.read())) file_res.seek(10) print('3) File Contents : {} \n'.format(file_res.read())) #PYTHON OUTPUT 1) File Contents : This is a text file 2) File Contents : This is a text file 3) File Contents : text file
read()
function second time you may not able to see file contents in your screen this is because the cursor will be at the end of the file in this case use seek()
function this will move the cursor to the start of the file.Closing File
To close the file which is after being processed is a necessary task as it terminates the process on file and makes sure of data is being saved without any exception.
Syntax:
file_object.close()
The close()
the function must be used at the end or after the process is completed.
Related Posts




