File Handling in Python open()

Learn Python @

File handling is a crucial aspect of programming, and Python offers a powerful tool for it: the open() function. Let’s delve into its intricacies to understand how it simplifies file operations.

Understanding open() Function

The open() function in Python is used to open files. Its syntax is as follows:

  • file: Path to the file you want to open.
  • mode: Optional parameter specifying the mode in which the file is opened.
  • buffering, encoding, errors, newline, closefd, opener: Additional optional parameters for advanced usage.

Modes of open()

Python’s open() function supports various modes for different file operations:

  • r: Read mode (default).
  • w: Write mode. Creates a new file or truncates an existing file.
  • a: Append mode. Creates a new file if it doesn’t exist.
  • b: Binary mode.
  • +: Reading and writing mode.
  • t: Text mode (default).

Example 1: Reading from a File

with open('sample.txt', 'r') as file:
    data =

Output 1:

Contents of sample.txt

Example 2: Writing to a File

with open('output.txt', 'w') as file:
    file.write("Hello, World!")

Example 3: Appending to a File

with open('output.txt', 'a') as file:
    file.write("\nAppending a new line.")

Points to Remember

  • The open() function is versatile, supporting various modes for reading, writing, and appending files.
  • Always use the with statement to ensure proper file closure after usage.
  • Be cautious while opening files in write mode ('w'), as it overwrites existing files.
Author: user