File objects in Python
Vijithkumar Vijayan
DST-INSPIRE fellow | Ph.D. Scholar in Bioinformatics | Blogger | YouTuber
What is a file object?
A file object is an object in Python that gives access to files. These could be the on-disk files, meaning files in the hard disk, or files present in other storage and communication devices. Once such a file object is created, then we can use different methods like read() and write(), to read from and write to the files, respectively.
Just like how we make a string object, by passing an argument to the string(), we use open(), a built-in function of the io module.
Different types of the file object
The io module has the main facilities - classes, methods, and attributes -to deal with input and output files. The io module provides the main tools to create file objects so that we can access files. These are the files in the disk and other storage and communication devices. Using different methods of the io module, we can also process the file. Before all this, we need to create a file object. I/O are of three types. It could be a text I/O, a binary I/O, or raw I/O. A single concrete object that belongs to any of these three categories is called a file object. The file object is called a text file if it helps us access a text IO. The file object is called a buffered binary file if it helps us access a binary I/O, and if the file object helps us access a raw I/O file, then the file object is called a raw binary file. So, again, a file object is created using the built-in function of the io module.
Once the file object is created, it is returned as an instance of io.TextIOWrapper class. Later one can use the methods and properties of the io.TextIOWrapper class, for reading string objects from, and to the text files.
What is an "io.TextIOWrapper class"
io.TextIOWrapper is a class within the io module. io.TextIOWrapper is a subclass of the Base class io.TextIOBase
io module has four Abstract Base Classes. io.IOBase, io.RawIOBase class, io.BufferedIOBase, io.TextIOBase These are the four Abstract Base Classes. io.TextIOBase is a base class for text files. This class provides a character and line-based interface to stream I/O. This Base class operates when a text file is opened in the “r” / “r+” /“w” /”a”/”a+” mode. io.TextIOWrapper inherits the class io.TextIOBase and the output is an object of the io.TextIOWrapper class.
How do you create a file object?
You create a file object using the open() built-in function. In the "open()" function, you also provide certain parameters or values within the parenthesis.
What are the parameters that you need to create a file object?
The format of the open() is as follows.
**open**(*file*,?*mode='r'*,?*buffering=-?1*,?*encoding=None*,?*errors=None*,?*newline=None*,?*closefd=True*,?*opener=None*)
There are eight arguments. All these are optional arguments.
Essentially, you can provide two parameters: one is the complete file path, which contains the detailed path where the file that is going to be read, written, or to be created, is located.
The second parameter is “mode”. The choice of "mode", depends upon what purpose you are creating the file object. Essentially, the important modes are, “r” mode, “r plus” mode, “w” mode, “w plus” mode, “a” mode, and “a plus” mode. By default value of the "mode" parameter is “r”
If you go through my previous tutorials, you will understand the details about each mode. But, I will briefly explain it here, in case you want.
“r” mode is for reading a file, “r+” (plus) is for reading and writing, “w” mode is for writing, “w +” mode is for writing and reading. “a” mode is for appending, and “a+” plus mode is for appending and reading.
How to create a file object with the two parameters
Call the open() function with the two parameters. One is the full path to the file, and the second is the mode. As you see here.
file=open(r"C:\\Users\\USER\\OneDrive\\Desktop\\text tutorial.txt", "r")
Here, what we have done is, we have created a file object. Keep in mind that, if you do not provide an argument for the "mode" parameter, Python is going to provide a default argument value of “r”.
The file object created using the open() function is an object of the '_io.TextIOWrapper’ class
When you create a file object, using the built-in open(), it returns an object of the class io.TetxtIOWrapper. Later you can apply the methods and properties of this class, to manage the file object. io.TextWrapper class is a subclass of the base class, io.TextIOBase and it inherits the methods and properties from it.
io.TextIOBase inherits from the Abstract Base Class, io.IOBase. This abstract base class contains all the methods and properties to manage/ create the Input/Output files. io.IOBase is the abstract base class of all classes of the io module. io provides four base classes: io.IOBase , io.BufferedIOBase, io.RawIOBase, and io.TextIOBase
You may look at the class hierarchy of the io module, in the flow chart provided.
领英推荐
_io.TextIOWrapper
How do we check if a file object has been created, and this is an object of the class io.TextIOWrapper?
file=open(r"C:\\Users\\USER\\OneDrive\\Desktop\\text tutorial.txt", "r")
print(type(file))
Contents of the file object can be read using read() method
Once the file object has been created, then the content of the file can be read using the read() method, as follows.
read() is a method of the Abstract Base Class, io.TextIOBase class.
file=open(r"C:\\Users\\USER\\OneDrive\\Desktop\\text tutorial.txt", "r")
content=file.read()
print(content)
The file object can be closed using the close() method
After the file object has been created and contents have been read or written to the file, we need to close the file object. The file object can be closed using the close() method. Once the file was closed, it is not possible to perform read or write.
close() is a method of the io.IOBaseclass, which is an Abstract Base Class
file=open(r"C:\\Users\\USER\\OneDrive\\Desktop\\text tutorial.txt", "r")
content=file.read()
print(content)
file.close()
file.read()
A file object closes automatically when the open function is used as a context manager.
If the built-in open() can be used as a context manager, the “with” statement, the file closes automatically, as and when it exits the “with” block. So, you do not need to close the file explicitly.
with open(r"C:\\Users\\USER\\OneDrive\\Desktop\\text tutorial.txt", "r")as file:
content=file.read()
print(file.readable())
print(file.readable())
So, in this code, we have used open() as a context manager. As and when it exits the with block, the file closes. For example, using the readable() method of the io.IOBaseclass, we can check it. Outside the block, readable() returns error
More about the "with" statement
Let us take a look at the “with” statement, in a little more detail. Normally, this is how we are supposed to write a code if want to open a file to write something in it.
file=open(r"C:\\Users\\USER\\OneDrive\\Desktop\\text tutorial2.txt", "w")
file.write("something")
file.close()
In this code, first, we open the file, then we write some content into it or we do some process, and finally, we close the file. Sometimes, while writing, or reading, or doing any process, Python throws certain errors. This prevents the file from being closed because the close method won’t get executed. In such a case, the file will still remain open, because the "file.close()" was not executed.
How do we check if the file was closed or not?
Let us try to run the above code, and delete the file. What happens is that, since the code was executed without any errors, the file was opened and closed properly. And the file was deleted without any error prompt. Now, let us purposefully create some errors, and check if it prevents the file from getting closed or not. How do we check it? Well, if the file was failed to close, we won’t be able to delete the file.
So, to make sure that the file closes, even if there is any error that pops up. For that we use the try - except-finally block.
file=open(r"D:\\After Effects\\after_effect project\\Python_file handling\\FIle_constructor\\files\\file.txt", "w")
try:
file.write(something)
except:
pass
finally:
file.close()
Here, we have opened a file in w mode. In the try block we have written something in the file. In the except block, it simply avoids any error. And, in the finally block, the file was closed.
We can replace try- except block with a “with” statement.
with open(r"D:\\After Effects\\after_effect project\\Python_file handling\\FIle_constructor\\files\\file.txt", "w")as file:
file.write("something")
Here, the open() constructor is used along with the with statement. And, even if there is any error, once we come out of the with block, the file automatically closes.
In python 3.x, you can use multiple comma-separated "with statements", like this.
with (open(r"D:\\After Effects\\after_effect project\\Python_file handling\\FIle_constructor\\files\\file.txt", "r")as file, open(r"D:\\After Effects\\after_effect project\\Python_file handling\\FIle_constructor\\files\\file2.txt", "w")as file2):
file2.write(file.read())
Here, what we have done is, we have used the open() function along with the "with statement". If we can use a class or function along with the "with" statement, then we call them context manager. So all the methods of that class or function can be used within the "with" block.