File handling is an integral part of programming. File handling in Python is simplified with built-in methods, which include creating, opening, and closing files.
While files are open, Python additionally allows performing various file operations, such as reading, writing, and appending information.
This article teaches you how to work with files in Python.
- Python 3 installed and set up.
- An IDE or code editor to write code.
- Access to a terminal to run the code (or run directly in an IDE).
- A text file for the examples.
Opening Files in Python
open() Python method is the primary file handling function. The basic syntax is:
file_object = open('file_name', 'mode')
open() function takes two elementary parameters for file handling:
file_name includes the file extension and assumes the file is in the current working directory. If the file location is elsewhere, provide the absolute or relative path.
mode is an optional parameter that defines the file opening method. The table below outlines the different possible options:
|Reads from a file and returns an error if the file does not exist (default).|
|Writes to a file and creates the file if it does not exist or overwrites an existing file.|
|Exclusive creation that fails if the file already exists.|
|Appends to a file and creates the file if it does not exist or overwrites an existing file.|
|Binary mode. Use this mode for non-textual files, such as images.|
|Text mode. Use only for textual files (default).|
|Activates read and write methods.|
The mode must have exactly one create(
a) method, at most one
+. Omitting the mode defaults to
'rt' for reading text files.
Below is a table describing how each of the modes behave when invoked.
|Pointer Position Start|
|Pointer Position End|
|Truncate (clear contents)|
|Must Not Exist|
The read mode in Python opens an existing file for reading, positioning the pointer at the file's start.
Note: If the file does not exist, Python throws an error.
To read a text file in Python, load the file by using the
f = open("<file name>")
The mode defaults to read text (
'rt'). Therefore, the following method is equivalent to the default:
f = open("<file name>", "rt")
To read files in binary mode, use:
f = open("<file name>", "rb")
+ to open a file in read and write mode:
f = open("<file name>", "r+") # Textual read and write
f = open("<file name>", "rt+") # Same as above
f = open("<file name>", "rb+") # Binary read and write
In all cases, the function returns a file object and the characteristics depend on the chosen mode.
Write mode creates a file for writing content and places the pointer at the start. If the file exists, write truncates (clears) any existing information.
Warning: Write mode deletes existing content immediately. Check if a file exists before overwriting information by accident.
To open a file for writing information, use:
f = open("<file name>", "w")
The default mode is text, so the following line is equivalent to the default:
f = open("<file name>", "wt")
To write in binary mode, open the file with:
f = open("<file name>", "wb")
+ to allow reading the file:
f = open("<file name>", "w+") # Textual write and read
f = open("<file name>", "wt+") # Same as above
f = open("<file name>", "wb+") # Binary write and read
open() function returns a file object whose details depend on the chosen modes.
Append mode adds information to an existing file, placing the pointer at the end. If a file does not exist, append mode creates the file.
Note: The key difference between write and append modes is that append does not clear a file's contents.
Use one of the following lines to open a file in append mode:
f = open("<file name>", "a") # Text append
f = open("<file name>", "at") # Same as above
f = open("<file name>", "ab") # Binary append
+ sign to include the read functionality.
Create mode (also known as exclusive create) creates a file only if it doesn't exist, positioning the pointer at the start of the file.
Note: If the file exists, Python throws an error. Use this mode to avoid overwriting existing files.
Use one of the following lines to open a file in create mode:
f = open("<file name>", "x") # Text create
f = open("<file name>", "xt") # Same as above
f = open("<file name>", "xb") # Binary create
+ sign to the mode include reading functionality to any of the above lines.
Reading Files in Python
After importing a file into an object, Python offers numerous methods to read the contents.
read() method on the file object and print the result. For example:
f = open("file.txt") print(f.read(),end="")
print() function automatically adds a new empty line. To change this behavior, add the
end="" parameter to
print() to remove the empty line.
The code prints the text file's contents.
Read Parts of the File
Provide a number to the
read() function to read only the specified number of characters:
f = open("file.txt") print(f.read(5))
The output prints the first five characters in the file.
Alternatively, use the
readline() method to print only the first line of the file:
f = open("file.txt") print(f.readline())
Add an integer to the
readline() function to print the specified number of characters without exceeding the first line.
To read lines and iterate through a file's contents, use a
f = open("file.txt") for line in f: print(line, end="")
Alternatively, use the
readlines() method on the file object:
f = open("file.txt") print(f.readlines())
The function returns the list of lines from the file stream.
Add an integer to the
readlines() function to control the number of lines. For example:
f = open("file.txt") print(f.readlines(15))
The integer represents the character number, and the function returns the line where the character ends along with the previous lines.
A file remains open until invoking the
close() function. It's good practice to close files no longer in use to avoid unpredictable file behavior and corrupted files.
To close a file, run the
close() method on the file object:
An alternative way to ensure a file closes is to use the
with statement. For example:
with open("<file name>"): file_contents = f.read() # Additional code here
with statement automatically closes the file.
Deleting Files in Python
Removing files in Python requires establishing communication with the operating system. Import the
os library and delete a file with the following:
import os os.remove("file.txt")
The file is no longer available. If the file does not exist, Python throws an error.
Python File Methods
Python offers various other functions when working with file objects. Below is a table that outlines all available processes and what they do.
|Flushes and closes the file object.|
|Separates buffer from text stream and returns the buffer.|
|Returns the file's descriptor if available.|
|Flushes the write buffer. Not available for read-only objects.|
|Checks if a file stream is interactive.|
|Checks if an object is readable.|
|Reads from the object until a newline or end of the file.|
|Returns a list of lines from the file object, where |
|Changes the pointer position to |
|Checks if the file object supports random access.|
|Prints the current stream position.|
|Resizes the file stream to |
|Checks whether the file object allows writing.|
|Writes a |
You know how to handle files in Python after reading this guide. Try using a Python library such as Pandas to work with other file types.