Seite wählen

I/O Python

ModeText/BinaryPurpose
'r'TextRead-only, file must exist
'w'TextWrite-only, overwrite existing file
'a'TextAppend-only, creates file if missing
'x'TextCreate file, fails if exists
'r+'TextRead & write, file must exist
'w+'TextWrite & read, overwrite file
'a+'TextAppend & read, create if missing
'rb'BinaryRead bytes
'wb'BinaryWrite bytes, overwrite file
'ab'BinaryAppend bytes
'xb'BinaryCreate binary file, fail if exists
'r+b'BinaryRead & write bytes
'w+b'BinaryWrite & read bytes
'a+b'BinaryAppend & read bytes

1️⃣Open a text file to read

with open("file.txt", "r") as f:  # default mode is 'r'
    content = f.read()  # read entire file
    print(content)
  • 'r' → read-only, file must exist
  • 'rt' → explicit text mode (default)

with is called a context manager in Python.

It ensures that resources are properly managed, even if an error occurs.

In file handling, it automatically closes the file after the block ends — you don’t need to call f.close() manually.

Without with:

f = open(„file.txt“, „r“)
content = f.read()
print(content)
f.close()

If an error occurs before f.close(), the file might stay open → resource leak.

Other read variants:

with open("file.txt", "r") as f:
    line = f.readline()    # read one line
    lines = f.readlines()  # read all lines into a list

2️⃣ Open a text file to write

with open("file.txt", "w") as f:
    f.write("Hello world\n")
  • 'w' → write-only, overwrites file if it exists
  • 'wt' → explicit text mode

3️⃣ Open a text file to append

with open("file.txt", "a") as f:
    f.write("Appended line\n")
  • 'a' → append-only, adds to end of file
  • 'a+' → append + read

4️⃣ Open a text file to read and write

with open("file.txt", "r+") as f:
    content = f.read()
    f.write("\nNew line at the end")
  • 'r+' → read & write, file must exist
  • 'w+' → write & read, overwrites file
  • 'a+' → append & read, file created if it does not exist

5️⃣ Open a text file for exclusive creation

with open("newfile.txt", "x") as f:
    f.write("This file did not exist before")
  • 'x' → fails if file exists
  • 'x+' → create exclusively with read/write

6️⃣ Open a file in binary mode

Read binary:

with open("file.bin", "rb") as f:
    data = f.read()

Write binary:

with open("file.bin", "wb") as f:
    f.write(b"Hello bytes")

Append binary:

with open("file.bin", "ab") as f:
    f.write(b"\nMore bytes")

Read & write binary:

with open("file.bin", "r+b") as f:
    data = f.read()
    f.write(b"\nNew binary content")

From the course

read(number)

  • Purpose: Reads data from a file.
  • Parameter: number (optional) — the maximum number of characters (text mode) or bytes (binary mode) to read.
  • Returns: A string (text mode) or bytes (binary mode) containing the read data.
  • Behavior:
    • If number is omitted or negative → reads the entire file.
    • Reading starts from the current file cursor position.
    • Subsequent read() calls continue from where the last read ended.

Example:

with open("file.txt", "r") as f:
    first_5_chars = f.read(5)  # reads first 5 characters
    next_chars = f.read(10)    # reads next 10 characters
  • Useful for reading large files in chunks instead of loading the whole file into memory

readline()

  • Purpose: Reads one line from the file at a time.
  • Parameter: Optional size — maximum number of characters to read from the line.
  • Returns: A string containing the line, including the newline character \n at the end (if present).
  • Behavior:
    • Each call reads the next line from the current file cursor.
    • When the end of file is reached, it returns an empty string ''.

Example:

with open("file.txt", "r") as f:
    line1 = f.readline()  # reads first line
    line2 = f.readline()  # reads second line
  • Useful when you want to process a file line by line, especially for large files, without loading the entire content into memory.

readlines(number)

  • Purpose: Reads multiple lines from a file and returns them as a list of strings.
  • Parameter: number (optional) — maximum number of bytes/characters to read from the file.
  • Returns: A list where each element is one line (including \n at the end of each line, if present).
  • Behavior:
    • If number is omitted → reads all remaining lines into a list.
    • If number is provided → reads approximately that many bytes/characters (may stop mid-file).
    • Stops when file ends.

Example:

with open("file.txt", "r") as f:
    all_lines = f.readlines()       # returns all lines as a list
    first_few = f.readlines(50)     # reads about 50 bytes worth of lines

👉 In practice, if you want to iterate line by line efficiently, it’s often better to do:

with open("file.txt", "r") as f:
    for line in f:
        print(line.strip())

(because readlines() loads everything into memory).

readinto(bytearray)

  • Purpose: Reads raw bytes from a file directly into a pre-allocated mutable buffer (like a bytearray or memoryview).
  • Parameter: bytearray — a writable buffer that will store the read bytes.
  • Returns: The number of bytes actually read.
  • Behavior:
    • Overwrites the content of the given buffer.
    • Reads at most len(bytearray) bytes.
    • Useful for binary data processing and performance-sensitive code (avoids creating new objects).

Example:

with open("file.bin", "rb") as f:
    buf = bytearray(16)        # allocate 16 bytes
    n = f.readinto(buf)        # read up to 16 bytes into buf
    print("Bytes read:", n)
    print("Buffer content:", buf)

If the file has fewer than 16 bytes, only that many will be read, and the rest of the buffer stays unchanged.

write(string)

  • Purpose: Writes a string (in text mode) or bytes (in binary mode) to the file.
  • Parameter: string (or bytes if file is opened in binary mode).
  • Returns: The number of characters/bytes written.
  • Behavior:
    • If the file is opened in text mode ("w", "a", "r+" etc.) → expects a string.
    • If the file is opened in binary mode ("wb", "ab", "r+b") → expects a bytes-like object (bytes, bytearray).
    • Data is buffered → not always written to disk immediately (use f.flush() or with to ensure closing).

Examples:

✅ Writing text:

with open("file.txt", "w") as f:
    n = f.write("Hello, World!\n")
    print("Characters written:", n)

✅ Writing binary:

with open("file.bin", "wb") as f:
    data = b"\x48\x65\x6C\x6C\x6F"  # "Hello" in hex
    n = f.write(data)
    print("Bytes written:", n)

⚡ Notes:

  • Overwrites content if the file is in "w" mode.
  • Appends content if the file is in "a" mode.
  • Does not automatically add a newline (\n), you must include it explicitly.

write(bytearray)

  • Purpose: Writes the contents of a bytes-like object (e.g., bytearray, bytes, memoryview) directly to a file.
  • Parameter: bytearray (or any buffer-supporting object).
  • Returns: The number of bytes written.
  • Behavior:
    • File must be opened in a binary mode ("wb", "ab", "rb+", etc.).
    • The entire bytearray (or up to its length) is written to the file.
    • Like write(string), data is buffered until the file is flushed or closed.

Example:

data = bytearray([65, 66, 67, 68])  # corresponds to "ABCD"

with open("file.bin", "wb") as f:
    n = f.write(data)
    print("Bytes written:", n)   # → 4

File content (in hex):

41 42 43 44

which is "ABCD" in ASCII.

open()

  • Purpose: Opens a file and returns a file object (also called a handle) that allows reading, writing, or updating the file.
  • Basic syntax:
open(file, mode="r", buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
ParameterDescription
filePath to the file (string or path-like object). Example: "file.txt"
modeHow the file is opened (read, write, append, binary, etc.). Default: "r" (read, text).
bufferingControls buffering:
0 → unbuffered (binary only)
1 → line-buffered (text only)
>1 → use buffer of that size
-1 (default) → system default
encodingText encoding (e.g., "utf-8", "latin-1"). Required for non-ASCII text.
errorsHow to handle encoding/decoding errors (e.g., "ignore", "replace").
newlineControls how newlines are handled in text mode (None, "", "\n", "\r", "\r\n").
closefdIf False, keeps file descriptor open (advanced use, rarely needed).
openerCustom opener function (rare, for low-level control).
error: Content is protected !!