I try such designs:

file = open('file.txt').read() open('copy_file.txt', 'w').write(file) 

For some reason, everything works ... From the experience of working with other languages, I expected to see some oddities in connection with open streams (I do not close them), but everything works fine. Even with repeated launch. And it doesn't seem like there is a memory leak problem. Why is that ? The documentation did not find anything on this topic ...

  • The file name is misleading. Use text instead. The file name can be used in Python for the result of calling the open () function. The read () method returns a string, not a file. - jfs

2 answers 2

Your memory is used only to store the contents of file.txt in the file variable.

And open threads are closed and collected by the garbage collector as soon as reading or writing ends, since you do not have references to these objects.

You can read about the assembly at this link: http://arctrix.com/nas/python/gc/

  • I understood. Thank. - faoxis
  • file is simply the contents of the file, in a single line. It naturally spends memory, which is equal to the size of this string. - Avernial
  • Do they close right away? That is, there is no need for with? - vitidev
  • 3
    @vitidev is not, the language does not guarantee this, and in particular, Pypy does not know when the file closes. On CPython, the file closes as soon as there are no links to it. On systems such as Windows, or if the script can open many files or in order not to think about the nontrivial details of the garbage collection implementation, you should close the files deterministically, for example, using the with-construction. - jfs
  • Yes, of course, PyPy is somewhat more complicated, since its garbage collector is not based on reference counting and when an object is deleted is a big question. Using with, it is more desirable, and the code is more visual and correct, the block in which the resource is opened is immediately visible. - Avernial

In the python implementation - PyPy, the collector does not close the files and therefore there may be a leak. Therefore, of course it is better to use the universal with. This is very helpful if you suddenly want to transfer the project to PyPy, since in most cases it is faster than the standard python implementation - CPython. Transfer in this case - just run on PyPy.

And also when you try to read an unclosed file in PyPy, you get an empty string. (if the file is open and for writing)

  • There are no references in the question code to the file, therefore there is no danger of blank input being received upon repeated reading. But there may be other problems - jfs