Supprimer Rendre public Rendre privé Add tags Delete tags
  Ajouter un tag   Annuler
  Supprimer le tag   Annuler
  • • DevOps notes •
  •  
  • Tags
  • Connexion

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)
2 months ago Permalien
cluster icon
  • Generics typing : Introduction to Generics Generic types let you write reusable, type-safe functions and classes that work uniformly across different data types. They ...
  • Filesystem Operations : Filesystem Operations (os & shutil) DevOps scripts often need to create, delete, copy, and move files and directories as part of automation workflows...
  • Python package and subpackage : Introduction to Packages (__init__.py) What is a Package? A Python package provides a way to structure a project's module namespace by using directori...
  • Running Python modules : Running Scripts: python -m vs. python file.py The Core Difference: What is "Entry Point Zero"? The key to understanding the difference lies in the fir...
  • Regex : Regex Essentials: Overview Regular expressions (regex) are a language for defining text search patterns. Python’s re module provides functions like...


(110)
Filtrer par liens sans tag
Replier Replier tout Déplier Déplier tout Êtes-vous sûr de vouloir supprimer ce lien ? Êtes-vous sûr de vouloir supprimer ce tag ? Le gestionnaire de marque-pages personnel, minimaliste, et sans base de données par la communauté Shaarli