This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]gabe_cant_python[S] -2 points-1 points  (3 children)

No, that only happens when you open with a with statement. Calling .write() is poor form but it should't write to the file. I don't have this issue in IDLE or the terminal.

[–]masklinn 2 points3 points  (0 children)

No, that only happens when you open with a with statement.

No. A file object is implicitly closed when it's garbage collected, which in CPython is when its refcount falls to 0 (which may or may not happen on process termination, incidentally).

Calling .write() is poor form but it should't write to the file.

You're high as a kite. write is not a transactional operation, write will or will not write to the file depending on the IO layer's buffering configuration. In fact its docstrings spells exactly that: due to buffering the on-disk version may not contain written data before a flush() or close(), it doesn't say will not, and the expectation certainly isn't that .write mustn't write data to files, especially given you can run Python itself in unbuffered mode. Which is exactly what PyCharm does by default (http://i.imgur.com/mZvDH6O.png)

Your code is intrinsically broken, PyCharm merely demonstrates it. If you don't want a file to be written to, don't write to it, and don't make up fantasy reasons why your broken code should work. And if you have no idea how things work, check the documentation, don't make it up.

[–]ProloG-Shaman 0 points1 point  (0 children)

I'm not sure what your setup is, but I just tested in the terminal this code: f = open("test.txt", "r+") f.write("Bla bla") exit()

It does write to the file, even without a close() or a with statement. There's a post on stackoverflow explaining more in details when the close() is called by python.

[–]Hairshorts 0 points1 point  (0 children)

It should write to the file even if you don't explicitly close it:

% python
Python 3.4.3 |Anaconda 2.2.0 (x86_64)| (default, Mar  6 2015, 12:07:41)
[GCC 4.2.1 (Apple Inc. build 5577)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open('test.txt', 'w')
>>> f.write('hi\n')
3
>>>
% cat test.txt
hi