Reference library

Files & data

Read and write files safely; parse JSON, CSV, and common text formats.

1 match
Files & data easy

How to Read a Text File Line by Line in Python

Reads a text file line by line with an enumerated for loop and prints each line number and content.

file-io text-files loops
Python
from pathlib import Path

def read_lines(file_path):
    with open(file_path, 'r', encoding='utf-8') as file:
        for line_number, line in enumerate(file, start=1):
            print(f"Line {line_number}: {line.rstrip()}")

if __name__ == "__main__":
    sample_file = Path("sample.txt")
    sample_file.write_text(…
14 0 Open

Browse by section

Each section groups closely related Python snippets.

Files & data — Python code examples

What you will find here

This page collects files & data snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.

Samples vs tutorials and challenges

Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.