Open/write deleting txt file contents?

python, python-3.x

Solution

Having empty files

This issue is caused by you failing to close the file descriptor. You have `f.close` but it should be `f.close()` (a function call). And you also need an `f2.close()` in the end.

Without the `close` it takes a while until the contents of the buffer arrive in the file. And it is a good practice to close file descriptors as soon as they are not used.

As a side note, you can use the following syntactic sugar to ensure that the file descriptor is closed as soon as possible:

with open(file, mode) as f:
    do_something_with(f)

Now, regarding the overwriting part:

Writing to file without overwriting the previous content.

Short answer: You don't open the file in the proper mode. Use the append mode (`"a"`).

Long answer:

It is the intended behavior. Read the following:

>>> help(open)
Help on built-in function open in module __builtin__:

open(...)
    open(name[, mode[, buffering]]) -> file object

    Open a file using the file() type, returns a file object.  This is the
    preferred way to open a file.  See file.__doc__ for further information.


>>> print file.__doc__
file(name[, mode[, buffering]]) -> file object

Open a file.  The mode can be 'r', 'w' or 'a' for reading (default),
writing or appending.  The file will be created if it doesn't exist
when opened for writing or appending; it will be truncated when
opened for writing.  Add a 'b' to the mode for binary files.
Add a '+' to the mode to allow simultaneous reading and writing.
If the buffering argument is given, 0 means unbuffered, 1 means line
buffered, and larger numbers specify the buffer size.  The preferred way
to open a file is with the builtin open() function.
Add a 'U' to mode to open the file for input with universal newline
support.  Any line ending in the input file will be seen as a '\n'
in Python.  Also, a file so opened gains the attribute 'newlines';
the value for this attribute is one of None (no newline read yet),
'\r', '\n', '\r\n' or a tuple containing all the newline types seen.

So, reading the manuals shows that if you want the content to be kept you should open in append mode:

open(file, "a")

Problem

I am bassicly trying to read a number from a file, convert it to an int, add one to it, then rewrite the new number back to the file. However every time I run this code when i open the .txt file it is blank. Any help would be appreciated thanks! I am a python newb. ``` f=open('commentcount.txt','r') counts = f.readline() f.close counts1 = int(counts) counts1 = counts1 + 1 print(counts1) f2 = open('commentcount.txt','w') <---(the file overwriting seems to happen here?) f2.write(str(counts1)) ```

Original source