In this tutorial, you’ll learn file objects. Also, we will see how to use file object methods and attributes to perform various file operations.
Series: Python File Handling
Table of contents
What is the File Object?
Python file object provides methods and attributes to access and manipulate files. Using file objects, we can read or write any files.
Whenever we open a file to perform any operations on it, Python returns a file object. To create a file object in Python use the built-in functions, such as open()
and os.popen()
.
IOError exception is raised when a file object is misused, or file operation fails for an I/O-related reason. For example, when you try to write to a file when a file is opened in read-only mode.
Types of File Object
In Python, there are three different categories of a file object, which are listed below:
- Text files
- Binary files
- Raw files
All file types objects are defined in the io module.
Text files (TextIOWrapper
)
The text file type is most common. Usually, we use text files to store character data or storing information in plain text with no special formatting beyond basic fonts and font styles.
We open a text file using the open()
function. For example, open('test'.txt', 'r')
. When we open a text file, it returns a TextIOWrapper
file object.
Example
file = open('test.txt', 'w')
print(type(file))
# Output: <class '_io.TextIOWrapper'>
Binary Files (BufferedReader
and BufferedWriter
)
Data is stored on a disk in the form of binary. For example, we use binary files to store data like images or videos. Binary files are a computer-readable form of storing data.
A program is needed to interpret the data in a binary file and display it to the user. The binary files are also called buffered files. This file type is used for reading and writing binary data.
Open the binary files using the open() function in binary mode. For example, open('abc.txt', 'rb')
. It opens the file to read-only in binary mode. The file pointer exists at the beginning of the file.
The open()
function will return the BufferedReader
when we open the binary file for reading and the BufferedWriter
file object when we open a binary file for writing.
Example
file = open('test.txt', 'rb')
print(type(file))
# Output: <class '_io.BufferedReader'>
Raw Files
A raw file is a collection of unprocessed data. It means the raw file has not been altered or manipulated in any way by the computer.
The raw files are also called unbuffered files, and this file type is generally used as a low-level building block for binary and text streams. Mostly, The raw file is not used.
When we open these files, using the open()
function will return a FileIO
object.
Example
file = open('test.txt', 'rb', buffering=0)
print(type(file))
# Output: <class '_io.FileIO'>
File Object Attributes
File object has the following attributes that we can use to accessing various details of a file, such as a file name and under which mode the file is opened.
name
: Return the name of the file. It is a read-only attribute and may not be present on all file-like objects. If the file object was created using theopen()
function, the file’s name is returned. Otherwise, some string indicates the source of the file object is returned.encoding
: It returns the encoding this file uses, such as UTF-8. This attribute is read-only. When Unicode strings are written to a file, they will be converted to byte strings using this encoding. It may also be None. In that case, the file uses the system default encoding for converting Unicode strings.mode
: Returns the file access mode used while opening a file.closed
: Returns True if a file is closed. It is a boolean value indicating the current state of the file object.newline
: Files opened in universal newline read mode keep track of the newlines encountered while reading the file. The values are ‘\r’, ‘\n’, ‘\r\n’, None (no newlines read yet), or a tuple containing all the newline types seen. For files not opened in universal newline read mode, the value of this attribute will beNone
Example:
with open(r'E:\pynative\files\test.txt', "r") as fp:
print('Is Closed:', fp.closed)
print('Encoding Used:', fp.encoding)
print('Access Mode:', fp.mode)
print('NewLines Found:', fp.newlines)
File Object Methods
File object has the following methods that we can use to accessing a file: A file can be opened with a built-in function called open()
. This function takes in the file’s path and the access mode and returns a file object.
Read More:
Method | Description |
---|---|
read() | Returns the file content. |
readable() | Returns whether the file stream can be read or not. |
readline() | Read single line |
readlines() | Read file into a list |
truncate(size) | Resizes the file to a specified size. |
writable() | Returns whether the file can be written to or not. |
write() | Writes the specified string to the file. |
writelines() | Writes a list of strings to the file. |
close() | Closes the opened file. |
seek() | Set file pointer position in a file |
seekable() | Returns whether the file allows us to change the file position. |
tell() | Returns the current file location. |
detach() | Returns the separated raw stream from the buffer |
fileno() | Returns a number that represents the stream, from the operating system’s perspective. |
flush() | Flushes the internal buffer. |
isatty() | Returns whether the file stream is interactive or not. |
Let’s see each method one by one.
read()
Method
Syntax:
file_object.read(size)
- The
size
represents the number of bytes to read from a file. It returns file content in a string object. - If
size
is not specified, it reads all content from a file - If the size argument is negative or not specified, read all data until EOF is reached.
- An empty string is returned when EOF is encountered immediately.
- When used in non-blocking mode, less data than requested may be returned, even if no size parameter was given.
Example:
# read(size)
with open(r'E:\pynative\files\test.txt', 'r') as fp:
# read 14 bytes
# fp is file object
print(fp.read(14))
# read all remaining content
print(fp.read())
Output:
My First Line My Second Line My Third Line
Read More:
- Complete Guide on Reading Files in Python
- Read Specific Lines From a File in Python
readline()
Method
Syntax:
file_object.readline(size)
- Read one line from a file at a time. It returns the line in a string format.
- If the
size
is given it reads the number of bytes (including the trailing newline) from a file. - If the size argument is negative or not specified, it read a single line
- An empty string is returned when EOF is encountered immediately.
Example:
# readline(size)
with open(r'E:\pynative\files\test.txt', 'r') as fp:
# read single line
print(fp.readline())
# read next line
print(fp.readline())
Output:
My First Line My Second Line
readlines()
Method
Syntax:
file_object.readlines(size)
- Read all lines from a file and return them in the form of a list object.
- If the
sizehint
argument is present, instead of reading the entire file, whole lines totaling approximately sizehint bytes (possibly after rounding up to an internal buffer size) are read
Example:
# read(size)
with open(r'E:\pynative\files\test.txt', 'r') as fp:
# read all lines
print(fp.readlines())
Output:
['My First Line\n', 'My Second Line\n', 'My Third Line']
readable() Method
It checks whether the file stream can be read or not.
Example:
# read(size)
with open(r'E:\pynative\files\test.txt', 'r') as fp:
# check if file object is readable
print(fp.readable())
# Output True
truncate(size)
Method
Use the truncate() method to make the file empty.
- If the optional size argument is present, the file is truncated to (at most) that size. So, for example, if you specify 10 bytes, truncate() will remove the first ten bytes from a file.
- The size defaults to the current position of a file pointer
- The current file position is not changed. Note that if a specified size exceeds the file’s current size, the result is platform-dependent: possibilities include that the file may remain unchanged, increase to the specified size as if zero-filled, or increase to the specified size with undefined new content. Availability: Windows, many Unix variants.
Example:
with open(r'E:\pynative\files\test.txt', 'a') as fp:
fp.truncate(5)
write()
Method
Write a string to the file. If buffering is used, the line may not show up in the file until the flush() or close() method is called.
Example:
with open(r'E:\pynative\files\test.txt', 'w') as fp:
fp.write('My New Line')
Read More: Complete guide on write to file in Python
writelines()
Method
- Write a list of strings to the file. Use to write multiple lines at a time to a file. You can write any iterable object producing strings, typically a list of strings.
- Note:
writelines()
do not add line separators.
Example:
with open(r'E:\pynative\files\test.txt', 'w') as fp:
data = ['line1\n', 'line2\n', 'line3\n']
fp.writelines(data)
writable()
Method
It checks whether the file can be written to or not.
Example:
# read(size)
with open(r'E:\pynative\files\test.txt', 'w') as fp:
# check if file object is readable
print(fp.writeable())
# Output True
close()
Method
Close the opened file. A closed file cannot be read or written anymore. The ValueError
will be raised if you try to read or write a closed file.
Example:
fp = open(r'E:\pynative\files\test.txt', 'r')
print(fp.read())
# close file
fp.close()
Note: It is good practice to open a file using the with
statement. It automatically closes the file and ensures that all the resources tied up with the file are released.
seek()
and tell()
method
The seek()
function sets the position of a file pointer and the tell()
function returns the current position of a file pointer.
Example:
with open(r'E:\pynative\files\test.txt', "r") as fp:
# Moving the file handle to 6th character
fp.seek(6)
# read file
print(fp.read())
# get current position of file pointer
print(fp.tell())
Read More: Complete Guide Python File Seek(): Move File Pointer Position
fileno()
Method
Return the integer file descriptor used by the underlying implementation system to request I/O operations from the operating system. This can be useful for other lower-level interfaces that use file descriptors, such as os.read()
.
Example:
with open(r'E:\pynative\files\test.txt', "r") as fp:
print(fp.fileno())
# Output 3
flush()
Method
As the name suggests, it flushes the internal buffer. When buffering is used, and if you are writing to a file. the line may not show up in the file until the flush() or close() method is called.
Example:
with open(r'E:\pynative\files\test.txt', "w") as fp:
fp.write('New Line')
fp.flush()
isatty()
Method
Return True if the file is connected to a TTY device like a teleprinter, else False. It let you know that whether the file stream is interactive or not.
Example:
with open(r'E:\pynative\files\test.txt', "r") as fp:
print(fp.isatty())
# Output False