I frequently see python code similar to
for line in open(filename):
do_something(line)
When does filename get closed with this code?
Would it be better to write
with open(filename) as f:
for line in f.readlines():
do_something(line)
filename would be closed when it falls out of scope. That normally would be the end of the method.
Yes, it's better to use with.
Once you have a file object, you perform all file I/O by calling methods of this object. [...] When you are done with the file, you should finish by calling the close method on the object, to close the connection to the file:
input.close()
In short scripts, people often omit this step, as Python automatically closes the file when a file object is reclaimed during garbage collection (which in mainstream Python means the file is closed just about at once, although other important Python implementations, such as Jython and IronPython, have other, more relaxed garbage collection strategies). Nevertheless, it is good programming practice to close your files as soon as possible, and it is especially a good idea in larger programs, which otherwise may be at more risk of having excessive numbers of uselessly open files lying about. Note that try/finally is particularly well suited to ensuing that a file gets closed, even when a function terminates due to an uncaught exception.
Python Cookbook, Page 59.
Drop .readlines(). It is redundant and undesirable for large files (due to memory consumption). The variant with 'with' block always closes file.
with open(filename) as file_:
for line in file_:
do_something(line)
When file will be closed in the bare 'for'-loop variant depends on Python implementation.
The with part is better because it close the file afterwards.
You don't even have to use readlines(). for line in file is enough.
I don't think the first one closes it.
python is garbage-collected - cpython has reference counting and a backup cycle detecting garbage collector.
File objects close their file handle when the are deleted/finalized.
Thus the file will be eventually closed, and in cpython will closed as soon as the for loop finishes.
Related
I have a txt file with size 100GB. I have to read it, do some processing and write in the same order as in original file in the most fastest way. For reading and writing I couldn't use multiprocessing, for processing I have tried map but I've got memory overflow, I've also tried with imap but it seems not speeding the process.
Don't load the file into memory all at once, but read it line by line. Don't store the output into memory all at once, but write it line by line. In the most basic form:
with open('input.txt', 'rt') as input_file:
with open('output.txt', 'wt') as output_file:
for input_line in input_file:
output_line = process(input_line)
# Assuming that output_line will have a trailing newline.
output_file.write(output_line)
If the processing is very CPU-intensive, you could gain performance with parallelization. But the I/O will have to remain sequential, so it's only worth it if you see that the program is taking 100% of a CPU core.
Forget about "speeding it up" for now, if you have to process a 100GB file your issue should be memory consumption. Your first issue is getting it to work at all.
You cannot read the whole file into memory, then process it (unless you happen to have 100GB RAM). You have to either read it line by line, or in batches and process only parts at a time.
So, instead of using file.read(), use file.readline() or file.read(some_size), depending on what that file that you read.
In the same way, if you need to write a processed 100GB file, don't collect all results in a list or something, write each line to the result file as soon as you are done processing a line of the original file.
Incidentally, I would expect this to the fastest method with your requirements (same order), because you can forget doing anything out of order and then sorting. You can't sort the data in-place if it's too big for your memory, and while sorting it on the file system is possible, it's more complicated and I am somewhat doubtful it would be faster.
In the comments of this question about a python one-liner, it occurred to me I have no idea how python handles anonymous file objects. From the question:
open(to_file, 'w').write(open(from_file).read())
There are two calls to open without using the with keyword (which is usually how I handle files). I have, in the past, used this kind of unnamed file. IIRC, it seemed there was a leftover OS-level lock on the file that would expire after a minute or two.
So what happens to these file handles? Are they cleaned up by garbage collection? By the OS? What happens to the Python machine and file when close() is called, and will it all happen anyway when the script finishes and some time passes?
Monitoring the file descriptor on Linux (by checking /proc/$$/fds) and the File Handle on Windows (using SysInternals tools) it appears that the file is closed immediately after the statement.
This cannot be guarenteed however, since the garbage collector has to execute. In the testing I have done it does get closed at once every time.
The with statement is recommended to be used with open, however the occasions when it is actually needed are rare. It is difficult to demonstrate a scenario where you must use with, but it is probably a good idea to be safe.
So your one-liner becomes:
with open(to_file, 'w') as tof, open(from_file) as fof:
tof.write(fof.read())
The advantage of with is that the special method (in the io class) called __exit__() is guaranteed* to be called.
* Unless you do something like os._exit().
The files will get closed after the garbage collector collects them, CPython will collect them immediately because it uses reference counting, but this is not a guaranteed behavior.
If you use files without closing them in a loop you might run out of file descriptors, that's why it's recommended to use the with statement (if you're using 2.5 you can use from __future__ import with_statement).
Do open files (and other resources) get automatically closed when the script exits due to an exception?
I'm wondering if I need to be closing my resources during my exception handling.
EDIT: to be more specific, I am creating a simple log file in my script. I want to know if I need to be concerned about closing the log file explicitly in the case of exceptions.
since my script has a complex, nested, try/except blocks, doing so is somewhat complicated, so if python, CLIB, or the OS is going to close my text file when the script crashes/errors out, I don't want to waste too much time on making sure the file gets closed.
If there is a part in Python manual that talks about this, please refer me to it, but I could not find it.
A fairly straightforward question.
Two answers.
One saying, “Yes.”
The other saying, “No!”
Both with significant upvotes.
Who to believe? Let me attempt to clarify.
Both answers have some truth to them, and it depends on what you mean by a
file being closed.
First, consider what is meant by closing a file from the operating system’s
perspective.
When a process exits, the operating system clears up all the resources
that only that process had open. Otherwise badly-behaved programs that
crash but didn’t free up their resources could consume all the system
resources.
If Python was the only process that had that file open, then the file will
be closed. Similarly the operating system will clear up memory allocated by
the process, any networking ports that were still open, and most other
things. There are a few exceptional functions like shmat that create
objects that persist beyond the process, but for the most part the
operating system takes care of everything.
Now, what about closing files from Python’s perspective? If any program
written in any programming language exits, most resources will get cleaned
up—but how does Python handle cleanup inside standard Python programs?
The standard CPython implementation of Python—as opposed to other Python
implementations like Jython—uses reference counting to do most of its
garbage collection. An object has a reference count field. Every time
something in Python gets a reference to some other object, the reference
count field in the referred-to object is incremented. When a reference is
lost, e.g, because a variable is no longer in scope, the reference count is
decremented. When the reference count hits zero, no Python code can reach
the object anymore, so the object gets deallocated. And when it gets
deallocated, Python calls the __del__() destructor.
Python’s __del__() method for files flushes the buffers and closes the
file from the operating system’s point of view. Because of reference
counting, in CPython, if you open a file in a function and don’t return the
file object, then the reference count on the file goes down to zero when
the function exits, and the file is automatically flushed and closed. When
the program ends, CPython dereferences all objects, and all objects have
their destructors called, even if the program ends due to an unhanded
exception. (This does technically fail for the pathological case where you have a cycle
of objects with destructors,
at least in Python versions before 3.4.)
But that’s just the CPython implementation. Python the language is defined
in the Python language reference, which is what all Python
implementations are required to follow in order to call themselves
Python-compatible.
The language reference explains resource management in its data model
section:
Some objects contain references to “external” resources such as open
files or windows. It is understood that these resources are freed when
the object is garbage-collected, but since garbage collection is not
guaranteed to happen, such objects also provide an explicit way to
release the external resource, usually a close() method. Programs are
strongly recommended to explicitly close such objects. The
‘try...finally‘ statement and the ‘with‘ statement provide convenient
ways to do this.
That is, CPython will usually immediately close the object, but that may
change in a future release, and other Python implementations aren’t even
required to close the object at all.
So, for portability and because explicit is better than implicit,
it’s highly recommended to call close() on everything that can be
close()d, and to do that in a finally block if there is code between
the object creation and close() that might raise an exception. Or to use
the with syntactic sugar that accomplishes the same thing. If you do
that, then buffers on files will be flushed, even if an exception is
raised.
However, even with the with statement, the same underlying mechanisms are
at work. If the program crashes in a way that doesn’t give Python’s
__del__() method a chance to run, you can still end up with a corrupt
file on disk:
#!/usr/bin/env python3.3
import ctypes
# Cast the memory adress 0x0001 to the C function int f()
prototype = ctypes.CFUNCTYPE(int)
f = prototype(1)
with open('foo.txt', 'w'):
x.write('hi')
# Segfault
print(f())
This program produces a zero-length file. It’s an abnormal case, but it
shows that even with the with statement resources won’t always
necessarily be cleaned up the way you expect. Python tells the operating
system to open a file for writing, which creates it on disk; Python writes hi
into the C library’s stdio buffers; and then it crashes before the with
statement ends, and because of the apparent memory corruption, it’s not safe
for the operating system to try to read the remains of the buffer and flush them to disk. So the program fails to clean up properly even though there’s a with statement. Whoops. Despite this, close() and with almost always work, and your program is always better off having them than not having them.
So the answer is neither yes nor no. The with statement and close() are technically not
necessary for most ordinary CPython programs. But not using them results in
non-portable code that will look wrong. And while they are extremely
helpful, it is still possible for them to fail in pathological cases.
No, they don't.
Use with statement if you want your files to be closed even if an exception occurs.
From the docs:
The with statement is used to wrap the execution of a block with
methods defined by a context manager. This allows common
try...except...finally usage patterns to be encapsulated for convenient reuse.
From docs:
The with statement allows objects like files to be used in a way that ensures they are always cleaned up promptly and correctly.
with open("myfile.txt") as f:
for line in f:
print line,
After the statement is executed, the file f is always closed, even if a problem was encountered while processing the lines. Other objects which provide predefined clean-up actions will indicate this in their documentation.
Yes they do.
This is a CLIB (at least in cpython) and operating system thing. When the script exits, CLIB will flush and close all file objects. Even if it doesn't (e.g., python itself crashes) the operating system closes its resources just like any other process. It doesn't matter if it was an exception or a normal exit or even if its python or any other program.
Here's a script that writes a file and raises an exception before the file contents have been flushed to disk. Works fine:
~/tmp/so$ cat xyz.txt
cat: xyz.txt: No such file or directory
~/tmp/so$ cat exits.py
f = open("xyz.txt", "w")
f.write("hello")
print("file is", open("xyz.txt").read())
assert False
~/tmp/so$ python exits.py
('file is', '')
Traceback (most recent call last):
File "exits.py", line 4, in <module>
assert False
AssertionError
~/tmp/so$ cat xyz.txt
hello
I, as well as other persons in this thread, are left with the question, "Well what is finally true?"
Now, supposing that files are left open in a premature program termination -- and there are a lot of such cases besides exceptions due to file handling -- the only safe way to avoid this, is to read the whole (or part of the) file into a buffer and close it. Then handle the contents in the buffer as needed. This is esp. the case for global search, changes, etc. that have to be done on the file. After changes are done, one can then write the whole buffer to the same or other file at once, avoiding the risk to leave the the newly created file open -- by doing a lot readings and writings -- which is the worst case of all!
I have a thread writing to a file(writeThread) periodically and another(readThread) that reads from the file asynchronously. Can readThread access the file using a different handle and not mess anything up?
If not, does python have a shared lock that can be used by writeThread but does not block readThread ? I wouldn't prefer a simple non-shared lock because file access takes order of a millisecond and the writeThread write period is of the same order(the period depends on some external parameters). Thus, a situation may arise where even though writeThread may release the lock, it will re-acquire it immediately and thus cause starvation.
A solution which I can think of is to maintain multiple copies of the file, one for reading and another for writing and avoid the whole situation all-together. However, the file sizes involved may become huge, thus making this method not preferable.
Are there any other alternatives or is this a bad design ?
Thanks
Yes, you can open the file multiple times and get independent access to it. Each file object will have its own buffers and position so for instance a seek on one will not mess up the other. It works pretty much like multiple program access and you have to be careful when reading / writing the same area of the file. For instance, a write that appends to the end of the file won't be seen by the reader until the write object flushes. Rewrites of existing data won't be seen by the reader until both the reader and writer flush. Writes won't be atomic, so if you are writing records the reader may see partial records. async Select or poll events on the reader may be funky... not sure about that one.
An alternative is mmap but I haven't used it enough to know the gotchas.
i am opening a csv file:
def get_file(start_file): #opens original file, reads it to array
with open(start_file,'rb') as f:
data=list(csv.reader(f))
header=data[0]
counter=collections.defaultdict(int)
for row in data:
counter[row[10]]+=1
return (data,counter,header)
does the file stay in memory if i quit the program inside the WITH loop?
what happens to the variables in general inside the program when i quit the program without setting all variables to NULL?
The operating system will automatically close any open file descriptors when your process terminates.
File data stored in memory (e.g. variables, Python buffers) will be lost. Data buffered in the operating system may be flushed to disk when the file is implicitly closed (checking the exact semantics of in-kernel dirty-buffers here would be educational, though you should not rely on it).
Your variables cease to exist when your process terminates.
My understanding of the with statement is that, no matter what, it will take care of closing your file handles for you when you exit it's scope. That should still happen if your program exits inside the with block.
As far as other variables are concerned, they're deleted from memory when your program exits automatically. If you are interested in finding ways to make something persistent between runs you can look at the pickle (http://docs.python.org/library/pickle.html) or shelve (http://docs.python.org/library/shelve.html) modules. Personally, I prefer shelve to pickle, but they both work well for that.
#gotgenes - Thanks for the suggestion. It's important to note that shelve uses pickle in its underlying implementation. When I say I prefer shelve to pickle, I mean that for the ways that persistence is important in what I'm currently designing using shelve is easier because it's not doing anything more than serving as a dictionary that persists between runs.
you never have to set variables to NULL, as soon as your program terminates the memory is freed. the same holds true for the file - it stays in memory no more or less whether you quit in the with loop or anywhere else. however, it is good practice to manually close the file so you can be sure that any pending operations are performed before the program is exited. in general, this should happen anyway, but especially when writing, I generally prefer the close.