DEV Community

Cover image for File Handling in Python: Reading, Writing, and Managing Data
Mary Nyandia
Mary Nyandia

Posted on

File Handling in Python: Reading, Writing, and Managing Data

Writing Files
Using open() with "w" mode, you can create or overwrite files. The with statement ensures files are closed properly.

filename = "sample.txt"

with open(filename, "w", encoding="utf-8") as file:
    file.write("Hello file handling!\n")
    file.write("This is a second line.\n")
print("Wrote to", filename)

Enter fullscreen mode Exit fullscreen mode

Reading Files
open() with "r" mode lets you read files. read() loads the entire content, while iterating reads line by line.

with open(filename, "r", encoding="utf-8") as file:
    content = file.read()
print("File content:")
print(content)

Enter fullscreen mode Exit fullscreen mode

Line‑by‑Line Reading
Reading files line by line is efficient for large files, as it avoids loading everything into memory at once.

with open(filename, "r", encoding="utf-8") as file:
    for line in file:
        print("Line:", line.strip())

Enter fullscreen mode Exit fullscreen mode

My take
File handling allows Python to interact with the outside world. You can:

  • Write data to files for storage.
  • Read files to process information.
  • Handle files line by line for efficiency. This skill is essential for building applications that log activity, store user data, or process text files.

Top comments (0)