Delete Set public Set private Add tags Delete tags
  Add tag   Cancel
  Delete tag   Cancel
  • • DevOps notes •
  •  
  • AI
  • Tags
  • Login

Read/Write Text Files/shaare/VogSQA

  • python
  • python

Read/Write Text Files

  • Use open() to read/write text files with proper modes and encoding.
  • Specify encoding='utf-8' for portability.
  • Leverage with to ensure files close automatically.
  • Read via iteration, .read(), .readline(), .readlines().
  • Write via .write() or .writelines(), managing newlines manually.
try:
    with open("config.txt", "w", encoding="utf-8") as file:
        file.write("Setting=Value\n")
        file.write("Other=Another\n")

    with open("config.txt", "r", encoding="utf-8") as file:
        content = file.read()
        print(f"Contents of file:")
        print(content)
except OSError as e:
    print(f"File error: {e}")

File Modes

  • 'r': read text (default), error if file missing.
  • 'w': write text, create or truncate.
  • 'a': append text, create if missing.
  • 'x': exclusive create, error if exists (good to prevent overwrites).
  • 'b': binary mode variant (e.g. 'rb', 'wb').
  • '+': update mode, allows read/write (e.g. 'r+', 'w+').

Understanding +

Mode Reads? Writes? Creates if missing? Truncates on open?
r ✅ ❌ ❌ ❌
r+ ✅ ✅ ❌ ❌
w ❌ ✅ ✅ ✅
w+ ✅ ✅ ✅ ✅
a ❌ ✅ ✅ ❌
a+ ✅ ✅ ✅ ❌
from pathlib import Path

path = Path("mode_demo.txt")

with path.open(mode="w", encoding="utf-8") as file:
    file.write("Initial line\n")

with path.open(mode="a", encoding="utf-8") as file:
    file.write("Appended line\n")

try:
    with path.open(mode="x", encoding="utf-8") as file:
        file.write("This will fail if file exists\n")
except FileExistsError as e:
    print(e)

Reading Text Files

  • Iteration: for line in f:

    • When to use: Ideal for processing large files line by line without loading the entire file into memory; lazy and very memory-efficient.
  • f.read(size = -1)

    • size can be used to specify the maximum number of characters to read; if negative or omitted, reads the entire file.
    • When to use: When you need to grab a chunk of text (e.g. next 1024 chars). Good for bulk reads; but beware of high memory usage if you read the whole file at once.
  • f.readline(size = -1)

    • size can be used to specify the maximum number of characters to read from the line; if negative or omitted, reads the full line up to and including the newline.
    • When to use: When you want one line at a time but need to guard against overly long lines. Returns an empty string when you reach EOF.
  • f.readlines(hint = -1)

    • hint can be used to define the approximate total number of bytes to read; if negative or omitted, reads all lines.
    • When to use: When the file is small or moderate in size and you want a list of all lines for easy indexing or list comprehensions. Not recommended for very large files (may exhaust memory).
from pathlib import Path

sample = Path("read_demo.txt")
sample.write_text("First\nSecond\nThird\n", encoding="utf-8")

print("Iteration for reading:")
with sample.open(mode="r", encoding="utf-8") as file:
    for line in file:
        print(f" -> {line.strip()}")

print("read() for reading:")
with sample.open(mode="r", encoding="utf-8") as file:
    print(file.read())

print("readline() for reading:")
with sample.open(mode="r", encoding="utf-8") as file:
    print(file.readline())

print("readlines() for reading:")
with sample.open(mode="r", encoding="utf-8") as file:
    print(file.readlines())

Writing Text Files

  • f.write(s)

    • s is the string to write; does not add a newline automatically.
    • When to use: When writing single strings or building content piece by piece. Returns the number of characters written, so you can verify success.
  • f.writelines(lines: Iterable[str]) -> None

    • lines can be any iterable of strings; does not add newlines for you.
    • When to use: When you need to write a batch of strings at once (for example, a list of CSV rows). It's more efficient than multiple calls to .write(), but you must include \n at the end of each string if you want line breaks.
from pathlib import Path

write_demo = Path("write_demo.txt")

with write_demo.open(mode="w", encoding="utf-8") as file:
    file.write("Line A\n")
    file.write("Line B\n")

lines_to_write = [
    "user,ip,role",
    "alice,10.0.0.0,admin",
    "bob,10.0.0.1,dev",
    "charlie,10.0.02,audit"
]
with write_demo.open(mode="w", encoding="utf-8") as file:
    file.writelines(f"{line}\n" for line in lines_to_write)
1 month ago Permalink
cluster icon
  • Working with CSV files : Working with CSV files CSV (Comma Separated Values) is a plain-text tabular format where each line is a row and fields are delimited (commonly by com...
  • Python Functions Are First‑Class Citizens : Python Functions Are First‑Class Citizens In Python, functions behave like any other object (strings, ints, lists). Because they are "first‑clas...
  • Generics typing : Introduction to Generics Generic types let you write reusable, type-safe functions and classes that work uniformly across different data types. They ...
  • The Iteration Protocol : The Iteration Protocol We use for item in sequence: all the time. But how does Python get each item? Iterable: An object that can be looped over. It...
  • Numbers, strings : Numbers (int and float) int: Whole numbers (e.g., 10, 1024). No overflow due to arbitrary precision. float: Numbers with decimals (e.g., 3.14159). Us...


(97)
Filter untagged links
Fold Fold all Expand Expand all Are you sure you want to delete this link? Are you sure you want to delete this tag? The personal, minimalist, super-fast, database free, bookmarking service by the Shaarli community