You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Always make sure you *explicitly* close each open file, once its job is done and you have no reason to keep it open.
43
42
Because
43
+
44
44
- There is an upper limit to the number of files a program can open. If you exceed that limit, there is no reliable way of recovery, so the program could crash.
45
45
- Each open file consumes some main-memory for the data-structures associated with it, like file descriptor/handle or file locks etc. So you could essentially end-up wasting lots of memory if you have more files open that are not useful or usable.
46
46
- Open files always stand a chance of corruption and data loss.
@@ -178,12 +178,10 @@ In this example we will copy a given text file to another file.
178
178
print("Wrong parameter")
179
179
print("./copyfile.py file1 file2")
180
180
sys.exit(1)
181
-
f1 = open(sys.argv[1])
182
-
s = f1.read()
183
-
f1.close()
184
-
f2 = open(sys.argv[2], 'w')
185
-
f2.write(s)
186
-
f2.close()
181
+
with open(sys.argv[1]) as f1:
182
+
s = f1.read()
183
+
with open(sys.argv[2], 'w') as f2:
184
+
f2.write(s)
187
185
188
186
.. note:: This way of reading file is not always a good idea, a file can be very large to read and fit in the memory. It is always better to read a known size of the file and write that to the new file.
0 commit comments