Lesson 10 - How to Work with Text Files in Python: A Beginner’s Guide

Learn how to read from and write to text files in Python. This beginner-friendly guide covers file handling basics, examples, and best practices.

PYTHON

Leonardo Gomes Guidolin

4/10/20251 min read

Introduction

Working with text files is a fundamental skill every Python programmer should master. Whether you're storing user input, reading configuration settings, or processing data, file handling is an essential tool in your coding toolkit.

In this tutorial, you'll learn how to open, read, write, and close text files in Python, using simple and clear examples. If you're just starting your coding journey, this guide is for you!

Why Learn to Work with Text Files?

Handling text files allows you to:

  • Save user data between sessions

  • Process large datasets

  • Export reports or logs

  • Interact with other systems through flat files

Let’s dive into the basics.

How to Open a Text File in Python

Python provides the built-in open() function to work with files.

file = open("example.txt", "r") # 'r' means read mode

Common modes include:

  • 'r' – Read (default)

  • 'w' – Write (overwrites file)

  • 'a' – Append

  • 'r+' – Read and write

Don’t forget to close the file after using it:

file.close()

Reading From a File

There are multiple ways to read a file in Python:

# Read entire content

file = open("example.txt", "r")

content = file.read()

print(content)

file.close()


# Read line by linefile = open("example.txt", "r")

for line in file:

print(line.strip())

file.close()


You can also use .readline() or .readlines() depending on your needs.

Writing to a File

To write to a file, use 'w' or 'a' mode:

# Overwrite or create file

file = open("example.txt", "w")

file.write("Hello, world!\n")

file.write("This is Python file handling.")

file.close()

# Append to an existing file

file = open("example.txt", "a")

file.write("\nNew line added.")

file.close()

Using the with Statement (Best Practice)

Using with automatically closes the file, even if an error occurs.

with open("example.txt", "r") as file:

content = file.read()

print(content)

This is the recommended way to handle files in Python.

Bonus: Checking If a File Exists

You can check if a file exists before opening it:

import os

if os.path.exists("example.txt"):

print("File exists!")

else:

print("File not found.")

Conclusion

Now you know how to open, read, write, and safely manage text files in Python! File handling is a core skill that will serve you well as your projects grow in complexity.

For more beginner-friendly Python tutorials, check out other posts on codeforbeginners.blog and keep coding!