Reading and Writing Text Files

Tutorial 1 of 5

1. Introduction

This tutorial aims to explore how to read and write text files in Python. Handling text files is an essential skill for any programmer as it allows you to store, access, and manipulate data. In Python, the built-in open() function is used to perform file handling tasks.

By the end of this tutorial, you will learn:

  • How to open a text file in Python
  • Various file modes in Python
  • How to read data from a file
  • How to write data to a file

Prerequisites: Basic knowledge of Python programming is required to follow this tutorial.

2. Step-by-Step Guide

Opening a File

In Python, we use the open() function to open a file. Its syntax is as follows:

open("filename", "mode")

File Modes

The mode parameter defines the type of action you want to perform on the file. Here are some common modes:

  • "r" - Read mode (default)
  • "w" - Write mode
  • "a" - Append mode
  • "x" - Create mode, creates a new file

Reading From a File

To read the entire content of a file, we use the read() method.

file.read()

Writing to a File

To write data to a file, we use the write() method.

file.write("Your text goes here")

Always remember to close the file after you are done with it using the close() method.

file.close()

3. Code Examples

Example 1: Reading a Text File

# Open the file in read mode
file = open("sample.txt", "r")

# Read the entire file content
content = file.read()

# Close the file
file.close()

# Print the content
print(content)

Here, we first open the file "sample.txt" in read mode. Then, we read the entire content of the file using read(), close the file using close(), and finally print the content.

Example 2: Writing to a Text File

# Open the file in write mode
file = open("sample.txt", "w")

# Write to the file
file.write("Hello, world!")

# Close the file
file.close()

In this example, we open the file in write mode, write "Hello, world!" to it, and then close it.

4. Summary

In this tutorial, we learned how to read and write text files in Python. We explored the open() function and the various modes in which a file can be opened. We learned how to read the content of a file using read() and write to a file using write(). We also saw the importance of closing a file after operations using close().

For further learning, consider exploring other file operations in Python like seeking, reading line by line, and working with binary files.

5. Practice Exercises

  1. Write a Python program to read the content of a file and print it in reverse order.
  2. Write a Python program to copy the content of one file to another.
  3. Write a Python program to count the number of lines in a text file.

Solutions and further practice exercises can be found here.