简体   繁体   中英

Confusion about with statement python

I have a question regarding the use of with statements in python, as given below:

with open(fname) as f:
    np.save(f,MyData)      

If I'm not mistaken this opens the file fname in a secure manner, such that if an exception occurs the file is closed properly. then it writes MyData to the file. But what I would do is simply:

np.save(fname,MyData)

This would result in the same, MyData gets written to fname . I'm not sure I understand correctly why the former is better. I don't understand how this one-liner could keep the file "open" after it has ran the line. Therefore I also don't see how this could create issues when my code would crash afterwards.

Maybe this is a stupid/basic question, but I always thought that a cleaner code is a nicer code, so not having the extra with -loop seems just better to me.

numpy.save() handles the opening and closing in its code , however if you supply a file descriptor, it'll leave it open because it assumes you want to do something else with the file and if it closes the file it'll break the functionality for you.

Try this:

f = open(<file>)
f.close()
f.read()  # boom

See also the hasattr(file, "write") ("file" as in descriptor or "handle" from file, buffer, or other IO ) check, that checks if it's an object with a write() method and judging by that Numpy only assumes it's true.

However NumPy doesn't guarantee misusing its API eg if you create a custom structure that's a buffer and doesn't include write() , it'll be treated as a path and thus crash in the open() call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM