In this tutorial, you’ll learn about file objects in Python. You’ll also 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?
A Python file object provides methods and attributes to access and manipulate a file. Using file objects, you can read from or write to any file.
Whenever you open a file to perform any operation on it, Python returns a file object. The most common way to create a file object is the built-in open() function.
An OSError exception (formerly called IOError) is raised when a file operation fails for an I/O-related reason, for example, when the file doesn’t exist. If you misuse a file object, for example, by trying to write to a file that is opened in read-only mode, Python raises io.UnsupportedOperation.
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 the most common. Text files store characters, such as plain text, CSV data, or source code, with no special formatting.
Open a text file using the open() function in text mode, for example, open('test.txt', 'r'). Text mode is the default. Opening a text file returns a TextIOWrapper file object, which reads and writes strings.
Example
Binary Files (BufferedReader and BufferedWriter)
Binary files store data as raw bytes. For example, images, videos, and executables are binary files. Their content is meant to be read by programs, not by people.
A program is needed to interpret the data in a binary file and display it to the user. In Python, binary file objects read and write bytes instead of strings, and they use a buffer to improve performance.
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
Raw Files
A raw file object gives low-level access to the underlying file, without any buffering or text decoding.
Raw files are also called unbuffered files. Python reads and writes them directly, without a buffer, so every operation goes straight to the operating system. They are mainly used as a low-level building block for binary and text streams, and you rarely need them in everyday code.
When you open a file in binary mode with buffering=0, the open() function returns a FileIO object.
Example
File Object Attributes
A file object has the following attributes that you can use to access details of a file, such as its name and the mode in which it was opened.
name: Returns the name of the file, as passed to theopen()function. It is a read-only attribute.encoding: Returns the encoding used to convert between text and bytes, such as UTF-8. It is available only for text files. If you don’t pass an encoding toopen(), Python uses the default encoding of your system.mode: Returns the access mode used while opening the file.closed: ReturnsTrueif the file is closed, andFalseotherwise.newlines: In text mode, keeps track of the line endings found while reading the file. Its value isNone(no line ending read yet), a string such as'\n'or'\r\n', or a tuple of all the line-ending types seen.
Example:
Output:
File Name: E:\pynative\files\test.txt Is Closed: False Encoding Used: utf-8 Access Mode: r NewLines Found: None Is Closed: True
File Object Methods
A file object has the following methods that you can use to work with a file. Remember that you get a file object by calling the built-in open() function with the file’s path and an access mode.
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)Code language: Python (python)
- The
sizeis the number of characters to read in text mode, or the number of bytes in binary mode. It returns the content as a string (text mode) or bytes (binary mode). - If
sizeis negative or not specified, it reads all content until the end of the file (EOF). - An empty string is returned when the end of the file has already been reached.
- When used in non-blocking mode, less data than requested may be returned.
Example:
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)Code language: Python (python)
- Reads one line from a file at a time and returns it as a string, including the trailing newline character.
- If
sizeis given, it reads at most that many characters from the line. - If the size argument is negative or not specified, it reads the whole line.
- An empty string is returned when the end of the file (EOF) is reached.
Example:
Output:
My First Line My Second Line
readlines() Method
Syntax:
file_object.readlines(size)Code language: Python (python)
- Reads all lines from a file and returns them as a list of strings. Each string keeps its trailing newline character.
- If the optional
sizehint is given, it stops reading once the total size of the lines read so far exceeds that value, instead of reading the entire file.
Example:
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:
truncate(size) Method
Use the truncate() method to resize a file, for example, to remove its content after a certain position or to make it empty.
- If the optional
sizeargument is given, the file is cut down to (at most) that many bytes. For example,truncate(10)keeps the first ten bytes and removes everything after them. - If
sizeis not given, it defaults to the current position of the file pointer. So,truncate(0)or callingtruncate()at the beginning of the file makes the file empty. - The current file position is not changed.
- If
sizeis larger than the current file size, the result depends on the platform. Usually, the file is extended with zero bytes. - The file must be opened for writing, for example, in
w,a, orr+mode.
Example:
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:
Read More: Complete guide on write to file in Python
writelines() Method
- Writes a list of strings to the file. Use it to write multiple lines at once. You can pass any iterable that produces strings, typically a list of strings.
- Note:
writelines()does not add line separators, so add\nto each string yourself.
Example:
writable() Method
It checks whether the file can be written to or not.
Example:
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:
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() Methods
The seek() function sets the position of a file pointer and the tell() function returns the current position of a file pointer.
Example:
Output:
6 st Line My Second Line My Third Line
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:
flush() Method
As the name suggests, it flushes the internal buffer. Python collects written data in a buffer and writes it to the disk in larger chunks. Until you call flush() or close(), the data may not appear in the file. Call flush() when another program needs to see the data immediately, for example, in a log file.
Example:
isatty() Method
Returns True if the file is connected to an interactive terminal (TTY) device, such as a console window or a teleprinter, and False otherwise. It tells you whether the file stream is interactive. For example, sys.stdout.isatty() is usually True when you run a script in a terminal.
Example:
Iterate Over a File Object
A text file object is also an iterator. When you loop over it with a for loop, it returns one line at a time. This is the most memory-efficient way to process a large file, because the whole file is never loaded into memory.
Output:
My First Line My Second Line My Third Line
Summary
- The
open()function returns a file object. Its type depends on the mode:TextIOWrapperfor text mode,BufferedReaderorBufferedWriterfor binary mode, andFileIOfor unbuffered binary mode. - Attributes such as
name,mode,closed, andencodingdescribe the file object. - Use
read(),readline(),readlines(), or a for loop to read, andwrite()orwritelines()to write. - Use
seek()andtell()to move and find the file pointer, andflush()to force buffered data to disk. - Always close a file, preferably by opening it with the
withstatement.
