| DJC | Tutorials | Python |

Reading and Writing Text Files in Python - DJC

Working with text files is one of the most common tasks. Python allows us to read their content or write new information into them.

Opening a File

To start working with a file, we first need to open it. This is done using the open() function.

# 'file_name.txt': name of the file
# 'mode': opening mode
# 'encoding': file encoding (commonly 'utf-8')
file = open('file_name.txt', 'mode', encoding='utf-8')

The most common opening modes are:

  • 'r' (read): Opens the file for reading only. The pointer is placed at the beginning of the file. If the file does not exist, it raises a FileNotFoundError.

  • 'w' (write): Opens the file for writing. If the file already exists, its content will be truncated (everything will be erased). If it doesn’t exist, a new one is created.

  • 'a' (append): Opens the file for appending content. The pointer is placed at the end of the file. If the file doesn’t exist, a new one is created.

  • 'x' (exclusive creation): Creates a new file and opens it for writing. If the file already exists, it raises a FileExistsError.

  • 'b' (binary): Opens the file in binary mode. It’s used in combination with the previous modes (e.g., 'rb', 'wb').

  • 't' (text): Opens the file in text mode (default). It’s used in combination with the previous modes (e.g., 'rt', 'wt').

Closing a File

It is crucial to close a file after finishing using it to free up system resources and ensure that all changes are saved.

file.close()

The with Statement (Context Manager)

The best practice for handling files is to use the with statement. This ensures the file is closed automatically, even if errors occur.

# Writing to a text file
with open('my_notes.txt', 'w', encoding='utf-8') as f:
    f.write("Hello, this is my first note.\n")
    f.write("Python file handling is awesome!\n")

# Reading from a text file
with open('my_notes.txt', 'r', encoding='utf-8') as f:
    content = f.read() # Reads the entire content
    print("Full content:")
    print(content)

print("-" * 30)

# Reading line by line
with open('my_notes.txt', 'r', encoding='utf-8') as f:
    print("Reading line by line:")
    for line in f:
        print(line.strip()) # .strip() removes leading/trailing whitespace including newlines

print("-" * 30)

# Appending to a text file
with open('my_notes.txt', 'a', encoding='utf-8') as f:
    f.write("This line was added later.\n")

with open('my_notes.txt', 'r', encoding='utf-8') as f:
    updated_content = f.read()
    print("Updated content after appending:")
    print(updated_content)

| DJC | Tutorials | Python |