Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
393 views
in Technique[技术] by (71.8m points)

python - In the Inline "open and write file" is the close() implicit?

In Python (>2.7) does the code :

open('tick.001', 'w').write('test')

has the same result as :

ftest  = open('tick.001', 'w')
ftest.write('test')
ftest.close()

and where to find documentation about the 'close' for this inline functionnality ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The close() here happens when the file object is deallocated from memory, as part of its deletion logic. Because modern Pythons on other virtual machines — like Java and .NET — cannot control when an object is deallocated from memory, it is no longer considered good Python to open() like this without a close(). The recommendation today is to use a with statement, which explicitly requests a close() when the block is exited:

with open('myfile') as f:
    # use the file
# when you get back out to this level of code, the file is closed

If you do not need a name f for the file, then you can omit the as clause from the statement:

with open('myfile'):
    # use the file
# when you get back out to this level of code, the file is closed

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...