HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to Python: Print and RepeatVariablesData Types & NumbersStringsListsConditions (if / elif / else)Loops (for / while)FunctionsOperatorsDictionariesTuples & SetsError Handling (try / except)Classes (Object-Oriented)File OperationsComments & IndentationBooleans (True / False)Lambda & map / filterModules (import)InheritanceVariable Scope
REFERENCE
📖 Overview
🖥️ Output & Input
🔢 Numbers & Math
✍️ String
📋 List
🗂️ Dictionary & Set
🔁 Condition & Loop
🧩 Function
📁 File & Error
🔄 Type & Conversion
Python›File Operations

File Operations

Creating, writing, reading a file with with open(), and the append modes (w / r / a).

Simple enough for a 5-year-old to understand

Write to and read from a file

with open(...) opens the file and closes it automatically when done. "w" is write mode, "r" is read mode.

Your first file
1
with open("not.txt", "w") as f:
Open "not.txt" in WRITE mode.
CodeOpen "not.txt" in WRITE mode.
2
f.write("Hello file")
Write the text into it.
CodeWrite the text into it.
3
with open("not.txt") as f:
Read the same file (default "r").
CodeRead the same file (default "r").
4
print(f.read())
Prints content to the screen: Hello file
Output / InputPrints content to the screen: Hello file
CodeOutput / Input
💡 Hint: "w" mode erases the file's OLD content. To add to the end, use "a" (append) mode.

🎯 Exercise & Practice

Test what you've learned — answer, write code, check instantly. (1 left)

1.Which mode is used to add to the end of a file WITHOUT erasing its old content?

About this topic

When your program closes, everything in memory is lost. The simplest way to make data permanent is to write it to a file: a log entry, a config file, a report. In Python, file operations are surprisingly short, and once you learn the right pattern, you use it the exact same way everywhere.

That pattern is the with block. You open the file with open, do your work inside with, and when the block ends, Python automatically closes the file—even if an error occurs. Writing close manually is both extra work and a risk; making the with block a habit is the most important step.

What you will learn

  • Opening files with with and open
  • Distinguishing read, write, and append modes (r, w, a)
  • Reading a file line by line
  • Writing to a file and moving to a new line
  • Why it is necessary to specify character encoding
  • Catching the error that occurs when a file does not exist

When to use?

File operations are used for keeping logs, storing user settings, generating a report, processing a large data file line by line, and transferring data between two programs.

If you are going to store structured data, using JSON or CSV formats instead of plain text saves you from the trouble of parsing the data when reading it back.

Common mistakes

Wrong

with open("notes.txt", "w") as f:
    f.write("new note")

The w mode CLEARS THE CONTENTS OF THE FILE WHEN OPENING IT. If you don't want to overwrite existing notes, you should use the append mode. This is the most common file error leading to data loss.

Correct

with open("notes.txt", "a") as f:
    f.write("new note")

Wrong

with open("veri.txt") as f:
    text = f.read()

When encoding is not specified, Python uses the operating system's default; on Windows, this is usually not UTF-8, and Turkish characters raise a "UnicodeDecodeError" or are read as corrupted. Always write the encoding explicitly.

Correct

with open("veri.txt", encoding="utf-8") as f:
    text = f.read()

Wrong

with open("big.txt") as f:
    for line in f.read().split("\n"):
        process(line)

read loads the entire file into memory; with a file of several gigabytes, the program crashes due to out-of-memory. The file object is already iterable line by line, and only a single line is kept in memory at a time.

Correct

with open("big.txt", encoding="utf-8") as f:
    for line in f:
        process(line.rstrip())

Frequently asked questions

What is the difference between r, w, and a modes?

r is for reading, raises an error if the file does not exist. w is for writing and deletes existing content, creates the file if it doesn't exist. a is for appending, writes to the end of the existing content. The two most frequently confused ones are w and a; the wrong choice leads to data loss.

How do I check if a file exists?

There are two approaches. To check beforehand, os.path.exists is used, but the file could be deleted between the check and the opening. The safer way is to try opening it directly and catch FileNotFoundError.

Why is there whitespace at the end of the lines I read?

Every line read from the file includes the newline character at the end. That is why comparisons do not yield the match you expect. Cleaning the end of the line with rstrip is the standard solution.

Summary

The correct pattern in file operations is the with and open duo: it guarantees closing. Not mixing up modes and explicitly specifying encoding are two essential habits that prevent data loss and Turkish character corruption.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code