← Back to Chapters

Python File Handling

? Python File Handling

⚡ Quick Overview

Python provides built-in support to work with files stored on your system. Using simple functions like open(), read(), and write(), you can store data permanently, load it back, and process it whenever needed.

  • Open files in different modes (read, write, append, etc.).
  • Read data from existing files.
  • Write new data or append to existing files.
  • Automatically close files safely using the with statement.

? Key Concepts

  • File object: Returned by open() and used to read/write data.
  • File modes: Control how you open the file, e.g. "r", "w", "a", "x", "rb", etc.
  • Text vs binary: Text files ("r", "w") vs binary files ("rb", "wb").
  • with statement: Context manager that automatically closes the file.
  • Read methods: read(), readline(), readlines() for different reading needs.

? Syntax and Theory

The basic syntax for opening a file in Python is:

? View Basic File Handling Syntax
file_object = open("filename.txt", "mode")
# perform file operations
file_object.close()

Common file modes include:

  • "r" – Read (default). Fails if the file does not exist.
  • "w" – Write. Creates a new file or overwrites an existing file.
  • "a" – Append. Adds content to the end of the file without deleting existing data.
  • "x" – Create. Creates a new file, error if the file already exists.
  • "rb", "wb", "ab" – Binary modes for read/write/append.

Using the with statement is the recommended way to handle files because it ensures the file is closed automatically, even if an error occurs.

? Code Examples

? Opening and Closing a File Manually

This example opens a file in read mode and then closes it explicitly.

? View Code Example
file = open("example.txt", "r")  # Open file in read mode
file.close()

? Using with Statement (Recommended)

Here, the with statement automatically closes the file once the block finishes.

? View Code Example
with open("example.txt", "r") as file:
    content = file.read()
print(content)  # File is automatically closed

? Reading from a File

Use readline() to read one line at a time and readlines() to get all lines in a list.

? View Code Example
with open("example.txt", "r") as file:
    print(file.readline())   # Reads one line
    print(file.readlines())  # Reads all remaining lines into a list

? Writing to a File

Opening a file in write mode ("w") will create the file if it does not exist.

? View Code Example
with open("example.txt", "w") as file:
    file.write("Hello, World!")  # Writes text to file

? Live Output and Explanation

? What these programs do

  • Opening and closing manually: open("example.txt", "r") tries to open the file.
  • Using with statement: Reads entire file content.
  • Reading line by line: Demonstrates readline() and readlines().
  • Writing to a file: Overwrites and writes new content.

? Tips & Best Practices

  • Always prefer using the with statement to automatically close files.
  • Choose the correct file mode depending on the operation.
  • Use read(), readline(), and readlines() appropriately.

? Try It Yourself

  • Create a new file and write multiple lines.
  • Read its content line by line.
  • Append more lines using "a" mode.

? Common Use Cases

  • Saving logs.
  • Storing settings.
  • Reading configuration files.
  • Processing text datasets.