Statement
There is no need to close files, with open statement 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 Files
Open multiple files in a single 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")
Last update: 377 days ago