Open a File in Read and Write Mode with Python



In Python, you can open a file for both reading and writing using the built-in open() function. This is essential when you want to manipulate a file's content without needing to close and reopen it repeatedly.

This mode allows us to read from and write to the file simultaneously, but it will raise an error if the file does not exist. We can also use Write and Read (w+) mode, which will truncate the file.

Opening a File in Read and Write Mode

To open a file for reading and writing, you can use the Read and Write Mode ('r+'). This mode allows you to read from and write to the file simultaneously. However, it's important to note that if the file does not already exist, it will raise a 'FileNotFoundError'.

Example

In this example, we first read the current content of 'example.txt', print it, and then write "Hello, World!" at the beginning of the file.

with open('example.txt', 'r+') as f:  
   # Read the current content of the file
   content = f.read()
   print("Current Content:", content)
   
   # Move the pointer back to the beginning of the file
   f.seek(0)
   
   # Write new content to the file
   f.write('Hello, World!')

Following is the output for the above code.

Current Content: (contents of example.txt before writing)

Using 'W+' Mode

Alternatively, we can use the Write and Read Mode ('w+') mode to open a file. This mode is similar to Read and Write Mode ('r+'), but it truncates the file if it already exists, meaning that any existing data will be erased. If the file does not exist, a new one will be created.

Example

The following example demonstrates the basic usage of the Write and Read mode ('w+').

# Open a file in write and read mode
with open('new_file.txt', 'w+') as f:
   # Write new content to the file
   f.write('New Content!')
   
   # Move the pointer back to the beginning of the file
   f.seek(0)
   
   # Read the content we just wrote
   content = f.read()
   print("Content after writing:", content)

Following is the output for the above code.

Content after writing: New Content!

Common File Access Modes in Python

In Python, the file mode indicates the purpose of opening a file and the operations that can be performed on it. When you open a file using the 'open()' function, you can specify the file mode as the second argument.

Read-only mode ('r')

By using read-only mode we can open a file for reading. The file pointer starts at the beginning. A `FileNotFoundError` will be raised if the file does not exist.

Example

The following example code reads the entire content of the file and prints it.

    # Open a file in write and read mode
with open('existing_file.txt', 'r') as f:
   content = f.read()
   print(content)

Following is the output of the above code.

This is the content inside the file.

Write only mode ('w')

The write-only mode Opens a file for writing. If the file exists, its content is erased. If the file does not exist, a new file is created. The file pointer is set at the start of the file.

Example

This code writes a new string to write_file.txt, replacing any existing content with the new string.

with open('write_file.txt', 'w') as f:
   f.write('This will overwrite any existing content.')

Following is the output of the above code.

The content of `write_file.txt` will be replaced with "This will overwrite any existing content.

Append only mode ('a')

By using append-only mode, it will Open a file to append data. Adds new data to the end of the file if it exists; if not, a new file is created. The file pointer is set to the end of the file for writing.

Example

The following example code appends a new line to the end of append_file.txt without altering any existing content.

with open('append_file.txt', 'a') as f:
   f.write('Appending this line to the file.\n')

Following is the output for the above code.

The line "Appending this line to the file." will be added to the end of 'append_file.txt'.

Append and read mode('a+')

This append and read mode ('a+) opens a file for both appending and reading. You can add data to the end of the file while also being able to read its contents.

Example

This code appends a new line to append_read_file.txt and then reads the whole file to print its content.

f = open('my_file.txt', 'w+')
with open('append_read_file.txt', 'a+') as f:
   f.write('This is a new line.\n')
   
   # Move the pointer to the beginning to read
   f.seek(0)
   content = f.read()
   print("Content of the file:", content)

Following is the output for the above code.

Content of the file: (existing content followed by "This is a new line.")
Updated on: 2025-02-20T18:13:44+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements