문제

What happens to a file descriptor when I don't assign it to a variable, but I just open it "in line"? How do I close it later?

For instance:

import csv
writer = csv.writer(open('a_file', 'wb'))
for line in some_data:
    writer.writerow(line)

I know I should use with, but what can I do in this particular case to close the file descriptor corresponding to a_file?

도움이 되었습니까?

해결책

Eventually is garbaged collected.

It is not a good practice to do this, because you may need to flush the contents of a file to be actually written to disk. By letting the garbage collector do its job when it wants, you're not sure when or whether the file will be actually written.

다른 팁

A file descriptor is like any other object in Python. When a reference to it goes out of scope, the reference count is decremented. When there are no more references to it, it is deleted.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top