In this post, we will learn about different modes to open a file in Python, how to write to text file in Python, and how to create a new file in Python, with detailed explanations and examples. So, let’s start learning all these things one by one.

Checkout Our previous post 👉 Read Text File in Python With Example

Different Modes to Open a File

There are various ways to open a file in Python. Here is a list of the most frequent ways to open a file in Python.

ModesDescription
rThis is the default mode. If you do not specify anything, the file is opened in reading mode.
w This mode allows you to write to your file. If the file does not exist, it creates a new one. However, if the file already contains content, it overwrites it with new content.
aThis mode allows you to write to your file and creates a new file if it does not already exist. Importantly, it appends new content to the end of the file without overwriting existing content.
r+This mode allows you to open a file for reading and writing. The file pointer is placed at the beginning of the file, allowing you to read from or write to it. One important thing to note is that it does not create a file if the file does not exist.
w+This mode allows you to open a file for reading and writing. It truncates the file to zero length if it exists, which means erasing all its content. Additionally, it creates a new file if it does not exist.

Now, let’s explore all the modes with examples for better understanding.

As we have already covered the reading mode (‘r’) in our previous blog post, let’s now move on to learning about the write mode (‘w’).

Write Mode (w)

Suppose we want to create a new file called ‘details.txt’ and add names and ages to it. We can easily do this using the write mode. Let’s see how.

with open("details.txt", "w") as wf:
    wf.write("Name: allinpython\n")
    wf.write("age: 23")

Output:

details.txt
Name: allinpython
age: 23

But if you use the write mode (‘w’) on an existing file, it will overwrite the existing content with new content. For example, we have ‘details.txt’ with existing content and then reopen it with write mode to add new content, it will overwrite the existing content.

with open("details.txt", "w") as wf:
    wf.write("this is updated content")

Output:

details.txt
this is updated content

Append Mode (a)

Let’s suppose we open our ‘details.txt’ file and want to add more content to it. We can easily do this using append mode (a). Let’s see how.

with open("details.txt", "a") as wf:
    wf.write("\nthis is append mode")

Output:

details.txt
this is updated content
this is append mode

This mode also creates a new file if it does not already exist. So, if you want to create a new file in Python, you can simply open a file with append mode (‘a’), close it, and it will create a new file. If the file already exists, it does not overwrite or modify it. let’s see how it work.

Create New File in Python

open("new_file.txt", "a").close()

This line creates a new file named ‘new_file.txt’. Also, remember to always use append mode (‘a’) to create a new file in Python. If you mistakenly use write mode (‘w’) and specify the name of an existing file, it will remove all its content. Therefore, using append mode is a good practice for creating new files.

Read and Write mode (r+)

The r+ mode in Python allows you to open a file for both reading and writing. This mode positions the file pointer at the beginning of the file, enabling you to read existing content and write new content wherever the file pointer is currently positioned. If the file does not exist, it raises a FileNotFoundError.

For example suppose we have a file named example.txt with the following content:

example.txt
Hello, allinpython!

And if you want to read the existing content of a file and then modify it, you can easily do so using ‘r+’ mode. Let’s see how.

# Open the file in 'r+' mode
with open('example.txt', 'r+') as file:
    # Read the existing content
    content = file.read()
    print("Original Content:", content) # NOTE: After reading all the content, the file pointer is at the end of the file.
    
    
    # Write new content to the file
    file.write("\nNew Content")
    
    # Move the file pointer to the beginning again (for reading)
    file.seek(0)
    
    # Read the updated content of the file
    updated_content = file.read()
    print("Updated Content:", updated_content)

Output:

Original Content: Hello, allinpython!
Updated Content: Hello, allinpython!
New Content

Write and Read mode (w+)

The w+ mode in Python allows you to open a file for both writing and reading. This mode creates a new file if it does not exist or truncates the file to zero length if it does. This means any existing content in the file is deleted when the file is opened. The file pointer is positioned at the beginning of the file, enabling you to write new content immediately and read from the beginning.

For example, suppose we have a file named example2.txt with the following content:

example2.txt
Hello, allinpython!

When we open this file in w+ mode, the existing content will be deleted. Let’s see how to use w+ mode:

# Open the file in 'w+' mode
with open('example2.txt', 'w+') as file:
    # Write new content to the file
    file.write("This is a new line of text.")
    
    # Move the file pointer to the beginning again (for reading)
    file.seek(0)
    
    # Read the new content of the file
    new_content = file.read()
    print("New Content:", new_content)

Output:

New Content: This is a new line of text.
Author

Hi, I'm Yagyavendra Tiwari, a computer engineer with a strong passion for programming. I'm excited to share my programming knowledge with everyone here and help educate others in this field.

Write A Comment