with syntax (Python)

Using the with syntax is convenient because you can omit close (), which you forget about, and it also improves readability.

Usage ```plaintext with file read as variable: ~~~~ ```

Example When writing "Hello, world!" To text.txt, it will be as follows.

python


#with statement used
with open("text.txt", 'w') as text:
    text.write("Hello, world!")

If you try to write this without the with statement, it will be as follows.

python


#with statement not used
text = None
try:
  text = open("text.txt", 'w')
  try:
    text.write("Hello, world!")
  except:
    raise
finally:
  if text:
    text.close()

Recommended Posts

with syntax (Python)
FizzBuzz with Python3
Scraping with Python
Statistics with python
Scraping with Python
Twilio with Python
Integrate with Python
Play with 2016-Python
AES256 with python
python starts with ()
Bingo with python
Zundokokiyoshi with python
Python syntax-control syntax
Excel with Python
Microcomputer with Python
Cast with python
Serial communication with Python
Django 1.11 started with Python3.6
Primality test with Python
Python with eclipse + PyDev.
Socket communication with Python
Data analysis with python 2
Scraping with Python (preparation)
Try scraping with Python.
Learning Python with ChemTHEATER 03
"Object-oriented" learning with python
Run Python with VBA
Handling yaml with python
Solve AtCoder 167 with python
Serial communication with python
[Python] Use JSON with Python
Learning Python with ChemTHEATER 05-1
Learn Python with ChemTHEATER
Run prepDE.py with python3
1.1 Getting Started with Python
Collecting tweets with Python
Binarization with OpenCV / Python
3. 3. AI programming with Python
Kernel Method with Python
Non-blocking with Python + uWSGI
Scraping with Python + PhantomJS
Posting tweets with python
Drive WebDriver with python
Use mecab with Python3
[Python] Redirect with CGIHTTPServer
Voice analysis with python
Think yaml with python
Getting Started with Python
Use DynamoDB with Python
Zundko getter with python
Handle Excel with python
Ohm's Law with Python
Primality test with python
Solve Sudoku with Python
Python starting with Windows 7
Heatmap with Python + matplotlib
Python programming with Atom
Learning Python with ChemTHEATER 02
Use Python 3.8 with Anaconda
Competitive programming with python
Handle rabbimq with python