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
open() / withtry / exceptraise
🔄 Type & Conversion
Python›REFERENCE›File & Error
📁

File & Error

Reading/writing files and catching errors.

CommandDescription
open() / withOpens, reads or writes a file.
try / exceptCatches errors so the program doesn't crash.
raiseDeliberately raises an error.

open() / with

Try it yourself →

Opens, reads or writes a file.

Syntax

with open(path, mod) as f:
    ...

Description

The with block opens the file and closes it automatically when done. mode: 'r' read, 'w' write (overwrite), 'a' append. f.read() reads it all, f.write() writes.

Parameters

pathThe file's name/path.
mode'r' read, 'w' write, 'a' append.

Example

with open("not.txt", "w") as f:
    f.write("Hello file")
with open("not.txt") as f:
    print(f.read())

Expected output

Hello file

When to use?

Keeping logs, settings/record files, exporting data.

Common mistakes

  • ⚠️ 'w' mode erases the file's old content; use 'a' to add to it.

try / except

Try it yourself →

Catches errors so the program doesn't crash.

Syntax

try:
    ...
except Error:
    ...

Description

You put risky code inside try; if an error occurs the except block runs and the program continues. finally runs in every case.

Example

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")

Expected output

Cannot divide by zero

When to use?

Preventing a crash when the user enters bad data, a file is missing, or the network drops.

Common mistakes

  • ⚠️ A bare 'except:' hides every error; if possible, specify the error type.

raise

Try it yourself →

Deliberately raises an error.

Syntax

raise Error("message")

Description

In an invalid situation you raise your own error; the calling code can catch it with try/except.

Example

def yas_ayarla(y):
    if y < 0:
        raise ValueError("Age cannot be negative")
    return y
try:
    yas_ayarla(-1)
except ValueError as e:
    print(e)

Expected output

Age cannot be negative

When to use?

Input validation, signaling 'this shouldn't have happened' situations.

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