Keyword with

with open('pi_digits.txt') as f:
    content = f.read()
    print(content)

Keywords with no need to access the file after it is closed. In this program, notice that we call the open (), but does not call close (); you can also call the open () and close () to open and close the file, but doing so, if there is a program bug, leading to close () statement is not executed, the file will not be closed. This may seem trivial, but did not properly close the file may result in data loss or damage. If you call close prematurely in the program (), you will find that you need to use the file it is closed (inaccessible), which can lead to more errors. Not always easy to determine the right time to close the file in any case, but by using the structure shown above, allows to determine Python: You just open the file and use it when needed, since Python automatically at the right time turn it off.

Published 145 original articles · won praise 6 · views 8060

Guess you like

Origin blog.csdn.net/sinat_23971513/article/details/105051761