Supprimer Rendre public Rendre privé Add tags Delete tags
  Ajouter un tag   Annuler
  Supprimer le tag   Annuler
  • • DevOps notes •
  •  
  • AI
  • 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)
1 month ago Permalien
cluster icon
  • If / Elif / Else Logic : If / Elif / Else Logic Control the flow of scripts based on conditions using if, elif, and else. The if Statement An if statement executes a block of ...
  • Logging to Files : Logging to Files Basic File Logging with FileHandler Use logging.FileHandler to write log records to a file. mode='a' (append) preserves existing log...
  • Variables, comments : Variables: Naming Values Naming Guidelines: Must start with a letter or underscore (_) and can contain letters, numbers, and underscores. Use snake_...
  • Signaling Errors: The raise Statement : Signaling Errors: The raise Statement Functions sometimes encounter states they cannot handle and must signal failure clearly. Using raise triggers...
  • Structured Logging : Introduction to Structured Logging Plain-text logs are hard to parse and brittle to format changes. Structured logging records events as key-value da...


(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