📖

How to Read Files in Python

PythonBeginner

Read content from text files safely.

Code Example

Python
# Create a sample file first
with open("sample.txt", "w") as f:
    f.write("Line 1: Hello\n")
    f.write("Line 2: World\n")
    f.write("Line 3: Python\n")

# Read entire file
with open("sample.txt", "r") as f:
    content = f.read()
    print("Entire file:")
    print(content)

# Read line by line
with open("sample.txt", "r") as f:
    print("\nLine by line:")
    for line in f:
        print(f"  {line.strip()}")

# Read all lines into list
with open("sample.txt", "r") as f:
    lines = f.readlines()
    print(f"\nAs list: {lines}")

# Check if file exists
import os
print(f"\nFile exists: {os.path.exists('sample.txt')}")

Explanation

Use "with open()" to safely read files. The file is automatically closed. Use read() for entire content, readline() for one line, readlines() for all lines.

Related Tutorials