# How Python Reads a File
# read(), readlines(), readline(), loop — all patterns in one place
# place soldiers.txt in the same folder as this script
# redhorndev.com

# ─────────────────────────────────────────────
# read() — whole file as one string
# ─────────────────────────────────────────────

with open("soldiers.txt", "r", encoding="utf-8") as f:
    content = f.read()

print(content)
# Raven
# Wolf
# Ghost
# Viper
# Bull

print(type(content))    # <class 'str'>

# ─────────────────────────────────────────────
# readlines() — all lines as a list
# ─────────────────────────────────────────────

with open("soldiers.txt", "r", encoding="utf-8") as f:
    lines = f.readlines()

print(lines)
# ['Raven\n', 'Wolf\n', 'Ghost\n', 'Viper\n', 'Bull\n']

# strip \n from each line
with open("soldiers.txt", "r", encoding="utf-8") as f:
    lines = [line.strip() for line in f.readlines()]

print(lines)
# ['Raven', 'Wolf', 'Ghost', 'Viper', 'Bull']

# ─────────────────────────────────────────────
# readline() — one line at a time
# ─────────────────────────────────────────────

with open("soldiers.txt", "r", encoding="utf-8") as f:
    first  = f.readline()
    second = f.readline()

print(first.strip())    # Raven
print(second.strip())   # Wolf

# ─────────────────────────────────────────────
# Loop over file — most common pattern
# ─────────────────────────────────────────────

with open("soldiers.txt", "r", encoding="utf-8") as f:
    for line in f:
        print(line.strip())

# Raven
# Wolf
# Ghost
# Viper
# Bull

# ─────────────────────────────────────────────
# Loop and build a list
# ─────────────────────────────────────────────

soldiers = []
with open("soldiers.txt", "r", encoding="utf-8") as f:
    for line in f:
        soldiers.append(line.strip())

print(soldiers)         # ['Raven', 'Wolf', 'Ghost', 'Viper', 'Bull']

# ─────────────────────────────────────────────
# Handling a missing file
# ─────────────────────────────────────────────

try:
    with open("missing.txt", "r", encoding="utf-8") as f:
        content = f.read()
except FileNotFoundError:
    print("File not found. Check the path.")

# ─────────────────────────────────────────────
# Quick reference
# ─────────────────────────────────────────────

# with open("file.txt", "r", encoding="utf-8") as f:
#     f.read()            — whole file as string
#     f.readlines()       — all lines as list (with \n)
#     f.readline()        — one line at a time
#     for line in f:      — line by line, memory efficient
#
# .strip()                — removes \n and whitespace
# FileNotFoundError       — file not found or wrong path
# put the file in the same folder as your script
