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?
- Types of File Object
- File Object Attributes
- File Object Methods
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
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 (
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.
file = open('test.txt', 'w') print(type(file)) # Output: <class '_io.TextIOWrapper'>
Binary Files (
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.
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.
file = open('test.txt', 'rb') print(type(file)) # Output: <class '_io.BufferedReader'>
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
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 the
open()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 be
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.
|Returns the file content.|
|Returns whether the file stream can be read or not.|
|Read single line|
|Read file into a list|
|Resizes the file to a specified size.|
|Returns whether the file can be written to or not.|
|Writes the specified string to the file.|
|Writes a list of strings to the file.|
|Closes the opened file.|
|Set file pointer position in a file|
|Returns whether the file allows us to change the file position.|
|Returns the current file location.|
|Returns the separated raw stream from the buffer|
|Returns a number that represents the stream, from the operating system’s perspective.|
|Flushes the internal buffer.|
|Returns whether the file stream is interactive or not.|
Let’s see each method one by one.
sizerepresents the number of bytes to read from a file. It returns file content in a string object.
sizeis 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.
# 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())
My First Line My Second Line My Third Line
- Complete Guide on Reading Files in Python
- Read Specific Lines From a File in Python
- Read one line from a file at a time. It returns the line in a string format.
- If the
sizeis 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.
# 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())
My First Line My Second Line
- Read all lines from a file and return them in the form of a list object.
- If the
sizehintargument 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
# read(size) with open(r'E:\pynative\files\test.txt', 'r') as fp: # read all lines print(fp.readlines())
['My First Line\n', 'My Second Line\n', 'My Third Line']
It checks whether the file stream can be read or not.
# read(size) with open(r'E:\pynative\files\test.txt', 'r') as fp: # check if file object is readable print(fp.readable()) # Output True
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.
with open(r'E:\pynative\files\test.txt', 'a') as fp: fp.truncate(5)
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.
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
- 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.
writelines()do not add line separators.
with open(r'E:\pynative\files\test.txt', 'w') as fp: data = ['line1\n', 'line2\n', 'line3\n'] fp.writelines(data)
It checks whether the file can be written to or not.
# 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 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.
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() function sets the position of a file pointer and the
tell() function returns the current position of a file pointer.
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
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
with open(r'E:\pynative\files\test.txt', "r") as fp: print(fp.fileno()) # Output 3
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.
with open(r'E:\pynative\files\test.txt', "w") as fp: fp.write('New Line') fp.flush()
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.
with open(r'E:\pynative\files\test.txt', "r") as fp: print(fp.isatty()) # Output False