How to Read, Write, and Process Files in Python

Markdown

View as Markdown

File handling is an important part of Python programming. It allows you to store information in files, retrieve existing data, and process file contents efficiently. This article explains how to create, read, write, and process text files in Python.

What is File Handling?

File handling allows Python programs to work with files stored on your computer.

Common file operations include:

  • Creating files

  • Opening files

  • Reading file contents

  • Writing data to files

  • Appending new data

  • Closing files

Understanding the open() Function

Python uses the open() function to work with files.

Syntax

open("filename.txt", "mode")

Common File Modes

Mode

Description

r

Read a file

w

Write to a file

a

Append data to a file

x

Create a new file

r+

Read and write

Creating and Writing to a File

The w mode creates a new file if it does not exist.

Example

Result

Reading a File

Use the r mode to read file contents.

Example

Reading a File Line by Line

Example

Writing Multiple Lines

Example

Result

 

Appending Data to a File

The a mode adds new content without removing existing data.

Example

Result

 

Using the with Statement

The with statement automatically closes the file after use.

Example

Benefits

  • Cleaner code

  • Automatically closes files

  • Recommended for most file operations

Reading All Lines into a List

Example

Processing File Data

Python can process file content after reading it.

Example

Searching for Text in a File

Example

Checking if a File Exists

Before opening a file, it is often helpful to verify that it exists.

Example

 

Python provides simple and powerful tools for working with files. The open() function allows you to create, read, write, and append data to files. Using the with statement is the recommended approach because it automatically manages file resources. File processing techniques such as reading line by line, counting records, and searching for data are commonly used in real-world Python applications.

Was this article helpful?

Still need help?

Contact us