Python
/
Storage
- 1 Language 9
-
Hello World S
-
Variables S
-
Functions S
-
Conditional A S
-
Operators S
-
While S
-
Turtle S
-
Script Mode S
-
Debugging S
- 2 Strings 7
-
Slice S
-
Raw Strings S
-
Regex A S
-
Validation S
-
Config S
-
Security S
-
Encrypt A S
- 3 Collections 6
-
Lists S
-
Dictionaries S
-
Efficiency S
-
Tree S
-
Tuples S
-
References S
- 4 Functions 5
-
Recursion S
-
Factorial S
-
Modulus S
-
Reassignment S
-
Approximate S
- 5 Storage 8
-
Files S
-
Databases S
-
Pipes S
-
With open S
-
Shelve A S
-
Zip S
-
Csv S
-
Json S
- 6 Class 4
-
Definition S
-
Attributes S
-
Functional S
-
Methods S
- 7 Goodies 5
-
Conditional Expression S
-
List Comprehension A S
-
Generator S
-
Named Tuple S
-
Modules S
- 8 Applications 5
-
Pythagora A S
-
Palindrome A S
-
Binary Search A S
-
Conway Game A S
-
Coin Flip A S
- 9 Scheduler 4
-
Time S
-
Multithreading A S
-
Subprocess S
-
Logging S
- 10 Packages 6
-
Clipboard A S
-
Ocr A S
-
Socket S
-
Image S
-
Virtualenv S
-
Jupyter S
S
R
Q
Python Storage With Open
No need to close the file Fewer lines of code, fewer bugs with open(file, 'w') as f: f.write('abc')
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