GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • About
  • Reference
  • Integrations
  • API
  • Blog
  • Python Syntax Reference
  • Feedback

This view

  • Original page
  • New address

GeezerVison is showing syntaxdb.com — With Statement in Python - SyntaxDB - Python Syntax Reference

  • Java
  • C
  • C++
  • C#
  • Python
  • Ruby
  • JavaScript
  • Swift
  • Go
Languages
    • User Program Communication
      • Print
      • User Input
      • Commenting
      • Read from Text File
      • Write to File
      • Import Module
    • Variables
      • Variable Declaration
      • Lists
      • List Comprehensions
      • Tuples
      • Dictionaries
      • Sets
    • Control Flow
      • If Statement
      • For Loop
      • While Loop
      • Ternary Operator
      • Try Catch Block
      • With Statement
      • Generators
    • Functions
      • Functions
      • First Class Functions
      • Lambda
      • Map
      • Filter
    • Object Oriented Programming
      • Class Declaration & Structure
      • Class and Instance Variables
      • Constructor
      • Instantiation
      • Methods
      • Inheritance
Categories
Language
Python
  • Java
  • C
  • C++
  • C#
  • Python
  • Ruby
  • JavaScript
  • Swift
  • Go
Version: 3.4.3

Categories

  • User Program Communication
    • Print
    • User Input
    • Commenting
    • Read from Text File
    • Write to File
    • Import Module
  • Variables
    • Variable Declaration
    • Lists
    • List Comprehensions
    • Tuples
    • Dictionaries
    • Sets
  • Control Flow
    • If Statement
    • For Loop
    • While Loop
    • Ternary Operator
    • Try Catch Block
    • With Statement
    • Generators
  • Functions
    • Functions
    • First Class Functions
    • Lambda
    • Map
    • Filter
  • Object Oriented Programming
    • Class Declaration & Structure
    • Class and Instance Variables
    • Constructor
    • Instantiation
    • Methods
    • Inheritance

Control Flow

With Statement in Python

Used to execute code with an unmanaged resource that may raise an exception. The with statement manages the resource, using it if successful and removing it when the block finishes executing.


Syntax
with resource as resource_var_name:
    #do something with resource

Notes

An example of a resource that may raise an exception is a file stream.


Example
with open('input.txt', 'r') as f:
    data = f.read()

Add to Slack

< Try Catch Block   |   Generators >


You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.