Skip to content

Commit 26801a3

Browse files
committed
more cleaning
1 parent e266e06 commit 26801a3

File tree

1 file changed

+6
-8
lines changed

1 file changed

+6
-8
lines changed

docs/file.rst

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -37,10 +37,10 @@ After opening a file one should always close the opened file. We use method *clo
3737
<_io.TextIOWrapper name='love.txt' mode='r' encoding='UTF-8'>
3838
>>> fobj.close()
3939

40-
.. important:: Important
41-
40+
.. important::
4241
Always make sure you *explicitly* close each open file, once its job is done and you have no reason to keep it open.
4342
Because
43+
4444
- 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.
4545
- 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.
4646
- 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.
178178
print("Wrong parameter")
179179
print("./copyfile.py file1 file2")
180180
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)
187185

188186
.. 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.
189187

0 commit comments

Comments
 (0)