Python
/
Storage
- 1 Language 9
-
Hello World
-
Variables
-
Functions
-
Conditional
-
Operators
-
While
-
Turtle
-
Script Mode
-
Debugging
- 2 Strings 6
-
Slice
-
Raw Strings
-
Regex
-
Validation
-
Config
-
Escape
- 3 Collections 5
-
Lists
-
Dictionaries
-
Efficiency
-
Tuples
-
References
- 4 Functions 5
-
Recursion
-
Factorial
-
Modulus
-
Reassignment
-
Approximate
- 5 Storage 8
-
Files
-
Databases
-
Pipes
-
With open
-
Shelve
-
Zip
-
Csv
-
Json
- 6 Class 4
-
Definition
-
Attributes
-
Functional
-
Methods
- 7 Goodies 5
-
Conditional Expression
-
List Comprehension
-
Generator
-
Named Tuple
-
Modules
- 8 Applications 5
-
Pythagora
-
Palindrome
-
Binary Search
-
Conway Game
-
Coin Flip
- 9 Scheduler 4
-
Time
-
Multithreading
-
Subprocess
-
Logging
- 10 Packages 2
-
Clipboard
-
Ocr
/
With open
➟
➟
Last update: 29-11-2021
With Open
! There is no need to close files, "with open" takes care of that.
"""With open statement benefits:
No need to close the file, 'with open' takes care of that.
Fewer lines of code,fewer bugs."""
import os
DIR = os.path.dirname(os.path.realpath(__file__))
file = DIR + "/data/file.txt"
with open(file, "w") as f:
f.write("New line 1 \n")
f.write("New line 2 \n")
with open(file) as f:
print(f.read())
# New line 1
# New line 2
Multiple
Open multiple files in a single with statement.
"""With open statement benefits:
Open multiple files in a single with statement.
"""
import os
DIR = os.path.dirname(os.path.realpath(__file__))
A = DIR + "/data/A.txt"
B = DIR + "/data/B.txt"
with open(A, "w") as fa, open(B, "w") as fb:
fa.write(os.path.basename(A) + ": Line 1")
fb.write(os.path.basename(B) + ": Line 1")
with open(A) as fa, open(B) as fb:
print(fa.read()) # myfileA.txt: Line 1
print(fb.read()) # myfileB.txt: Line 1
Exception
! File will be closed before handling the exception.
"""Using with open statement
you have excellent handling in case of exception."""
import os
DIR = os.path.dirname(os.path.realpath(__file__))
file = DIR + "/data/file.txt"
with open(file, "w") as f:
f.write("0")
try:
print("Open file to read ...")
with open(file) as f:
data = f.read()
x = 1 / data # 1 / 0
print(data) # line not reached
except:
print("Error!")
if f.closed == False:
print("File not closed - not ok")
else:
print("File closed before exception - ok")
➥ Questions github Storage