- Python file modes | Open, Write, append (r, r+, w, w+, x, etc)
- Python file modes
- Let’s See a basic Example of the use of File mode
- Create File
- Write File
- File Handling in Python: Create, Open, Append, Read, Write
- Opening Files in Python
- Read Mode
- Write Mode
- Append Mode
- Create Mode
- Reading Files in Python
- Read Parts of the File
- Read Lines
- Close Files
- Deleting Files in Python
- Python File Methods
Python file modes | Open, Write, append (r, r+, w, w+, x, etc)
When you do work with the file in Python you have to use modes for specific operations like create, read, write, append, etc. This is called Python file modes in file handling.
Python file modes
Don’t confuse, read about every mode below.
- r for reading – The file pointer is placed at the beginning of the file. This is the default mode.
- r+ Opens a file for both reading and writing. The file pointer will be at the beginning of the file.
- w Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, create a new file for writing.
- w+ Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, it creates a new file for reading and writing.
- rb Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file.
- rb+ Opens a file for both reading and writing in binary format.
- wb+ Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not exist, it creates a new file for reading and writing.
- a Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
- ab Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
- a+ Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.
- ab+ Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.
- x open for exclusive creation, failing if the file already exists (Python 3)
You can combine the modes as needed by specifying them in a string. For example, «rb» represents opening a file in binary mode for reading.
Let’s See a basic Example of the use of File mode
Create File
Write File
Now writing the file. ‘w’ – Write mode
f = open("testFile.txt", "w") f.write("Hello file")
Here are a few examples of opening files with different modes:
# Read mode file = open("example.txt", "r") # Write mode (creates a new file if it doesn't exist) file = open("example.txt", "w") # Append mode (creates a new file if it doesn't exist) file = open("example.txt", "a") # Binary mode for reading file = open("example.bin", "rb") # Read and write mode file = open("example.txt", "r+")
Do comment if you have any doubts or suggestions on this tutorial.
Note:
IDE: PyCharm 2020.1.1 (Community Edition)
macOS 10.15.4
Python 3.7
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
File Handling in Python: Create, Open, Append, Read, Write
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.
Note: Follow one of our guides to install Python 3 for:
Opening Files in Python
The open() Python method is the primary file handling function. The basic syntax is:
file_object = open('file_name', 'mode')
The open() function takes two elementary parameters for file handling:
1. The 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.
2. The mode is an optional parameter that defines the file opening method. The table below outlines the different possible options:
Mode | Description |
---|---|
‘r’ | Reads from a file and returns an error if the file does not exist (default). |
‘w’ | Writes to a file and creates the file if it does not exist or overwrites an existing file. |
‘x’ | Exclusive creation that fails if the file already exists. |
‘a’ | Appends to a file and creates the file if it does not exist or overwrites an existing file. |
‘b’ | Binary mode. Use this mode for non-textual files, such as images. |
‘t’ | Text mode. Use only for textual files (default). |
‘+’ | Activates read and write methods. |
The mode must have exactly one create( x )/read( r )/write( w )/append( 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.
Behavior | Modes |
---|---|
Read | r , r+ , w+ , a+ , x+ |
Write | r+ , w , w+ , a , a+ , x+ |
Create | w , w+ , a , a+ , x , x+ |
Pointer Position Start | r , r+ , w , w+ , x , x+ |
Pointer Position End | a , a+ |
Truncate (clear contents) | w , w+ |
Must Exist | r , r+ |
Must Not Exist | x , x+ |
Read Mode
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 open() function:
The mode defaults to read text ( ‘rt’ ). Therefore, the following method is equivalent to the default:
To read files in binary mode, use:
Add + to open a file in read and write mode:
f = open("", "r+") # Textual read and write
f = open("", "rt+") # Same as above
f = open("", "rb+") # Binary read and write
In all cases, the function returns a file object and the characteristics depend on the chosen mode.
Note: Refer to our article How to Read From stdin in Python to learn more about using stdin to read files.
Write 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:
The default mode is text, so the following line is equivalent to the default:
To write in binary mode, open the file with:
Add + to allow reading the file:
f = open("", "w+") # Textual write and read
f = open("", "wt+") # Same as above
f = open("", "wb+") # Binary write and read
The open() function returns a file object whose details depend on the chosen modes.
Append Mode
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("", "at") # Same as above
f = open("", "ab") # Binary append
Add the + sign to include the read functionality.
Note: Learn how to append a string in Python.
Create Mode
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("", "xt") # Same as above
f = open("", "xb") # Binary create
Add the + 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.
Use the read() method on the file object and print the result. For example:
f = open("file.txt") print(f.read(),end="")
Note: The 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.
Read Lines
To read lines and iterate through a file’s contents, use a for loop:
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.
Close Files
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_contents = f.read() # Additional code here
The with statement automatically closes the file.
Note: Learn 3 methods on how to find list length in Python.
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.
Method | Description |
---|---|
close() | Flushes and closes the file object. |
detach() | Separates buffer from text stream and returns the buffer. |
fileno() | Returns the file’s descriptor if available. |
flush() | Flushes the write buffer. Not available for read-only objects. |
isatty() | Checks if a file stream is interactive. |
read() | Read number of characters at most. |
readable() | Checks if an object is readable. |
readline() | Reads from the object until a newline or end of the file. |
readlines() | Returns a list of lines from the file object, where is the approximate character number. |
seek(, ) | Changes the pointer position to relative to the . |
seekable() | Checks if the file object supports random access. |
tell() | Prints the current stream position. |
truncate() | Resizes the file stream to (or current position if unstated) and returns the size. |
write() | Writes to the file object and returns the written number of characters. |
writable() | Checks whether the file object allows writing. |
writelines() | Writes a of lines to the stream without a line separator. |
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.
For more Python tutorials refer to our article and find out how to add items to Python dictionary.