Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

File Input and Output Operations in Python

Tech 1

Files serve as persistent storage beyond the runtime memory of a program. Python provides a built-in streaming interface for creating, reading, updating, and removing files on disk.

Stream Initialization

Invoke open() to obtain a file handle:

handle = open("report.txt", mode="r", encoding="utf-8")

The mode argument controls access behavier:

  • r — read from the beginning (default)
  • w — truncate and open for writing
  • a — preserve existing bytes and append
  • x — exclusive creation; raises FileExistsError if the path is taken
  • b — binary access (e.g., rb, wb)
  • t — text decoding with the specified encoding (default)

After finishing, explicitly release system resources:

handle.close()

Sequential Reading

Slurp the entire contents into a string:

f = open("dataset.csv", "rt", encoding="utf-8")
payload = f.read()
print(payload)
f.close()

Process one record at a time to keep memory usage low:

f = open("dataset.csv", "rt", encoding="utf-8")
for record in f:
    print(record.strip())
f.close()

Persisting Data

Overwrite mode (w) creates the file if absent, otherwise empties it:

f = open("notes.txt", "wt", encoding="utf-8")
f.write("Meeting scheduled for 10 AM\n")
f.write("Prepare slide deck\n")
f.close()

Append mode (a) inserts bytes at the current end-of-file:

f = open("notes.txt", "at", encoding="utf-8")
f.write("Follow-up required\n")
f.close()

Automatic Resource Management

A context manager guarantees closure regardless of control flow:

with open("dataset.csv", "r", encoding="utf-8") as f:
    payload = f.read()
    print(payload)

The same pattern applies to output:

with open("notes.txt", "w", encoding="utf-8") as f:
    f.write("Line one\n")
    f.write("Line two\n")

Metadata and Cleanup

Validate existence before destructive actions:

from pathlib import Path

source = Path("notes.txt")
if source.is_file():
    print("Located on disk")
else:
    print("Not found")

Remove a file permanently:

from pathlib import Path

target = Path("temp.txt")
if target.exists():
    target.unlink()
    print("Deleted")

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.