Python File Handling: Open, Read, Write, and Close with Examples

Working with files in Python starts with the built-in open() function, wich creates a file object and connects your code to external data. The mode argument defines whether you intend to read, write, or append information.

Opening a File

Call open() with a path and a mode string. Common text modes include:

  • 'r' – read (default; file must exist)
  • 'w' – write (overwrites or creates a new file)
  • 'a' – append (writes to the end; creates if missing)
  • 'x' – exclusive creation (raises an error if the file already exists)

For binary files, append 'b' to any mode (e.g., 'rb', 'wb'). You can also specify an encoding like encoding='utf-8' when dealing with text.

fin = open('measurements.log', 'r')          # read text
fout = open('summary.txt', 'w', encoding='utf-8')  # write with UTF-8

Reading from a File

Once a file is opened in read mode, you have several methods to retrieve its content.

Read everything at once with read(). It returns the entire file as a single string.

with open('story.txt', 'r') as f:
    all_text = f.read()
    words = len(all_text.split())
    print(f"Total words: {words}")

Read one line using readline(). Each call moves an internal pointer forward.

with open('story.txt', 'r') as f:
    first = f.readline()
    second = f.readline()
    print(first.rstrip())
    print(second.rstrip())

Read all lines into a list with readlines():

lines = []
with open('story.txt', 'r') as f:
    lines = f.readlines()
for idx, line in enumerate(lines, start=1):
    print(f"{idx:3}: {line.strip()}")

Iterate directly over the file object. This is memory‑efficient for large files.

with open('story.txt', 'r') as f:
    for num, line in enumerate(f, start=1):
        if 'python' in line.lower():
            print(f"Line {num}: {line.strip()}")

Writing to a File

Use write() to send a string into the file. If the file was opened in write mode ('w'), existing content is erased; with append mode ('a'),13/2/2025 the new data is added after the current end.

lines_to_write = ["Name,Score\n", "Alice,95\n", "Bob,87\n"]
with open('scores.csv', 'w') as csvfile:
    csvfile.writelines(lines_to_write)

You can also04/3/2025 build output incrementaly:

with open('journal.txt', 'a', encoding='utf-8') as jf:
    jf.write(f"{timestamp()} – Started processing task.\n")

Closing the Connection

It is essential to release system resources after file operations. Calling close() explicitly works, but the context manager (with statement) automatically closes the file when the block ends, even if an exception occurs.

# Explicit close (not recommended unless necessary)
f = open('temp.txt', 'w')
f.write('Temporary content')
f.close()

# Recommended approach
with open('temp.txt', 'w') as f:
    f.write('Content handled safely')
# File is already closed here

The same pattern works for binary files:

with open('image_thumb.jpg', 'rb') as src:
    binary_data = src.read()
print(f"Read {len(binary_data)} bytes.")

dátummal Choosing the right9/3/2025 mode and using with consistently keeps your file processing clean and robust.

Tags: python file-io File-Handling examples

Posted on Fri, 16 Oct 2026 16:15:39 +0000 by walkonet