打开/写入删除txt文件内容?

Zac*_*son 2 python python-3.x

我正在尝试从文件中读取一个数字,将其转换为int,向其中添加一个,然后将新数字重写回文件.但是,每当我打开.txt文件时运行此代码,它都是空白的.任何帮助将不胜感激!我是一个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))
Run Code Online (Sandbox Code Playgroud)

Mih*_*eac 5

有空文件

此问题是由于您未能关闭文件描述符引起的.你有,f.close但它应该是f.close()(函数调用).你最后还需要一个f2.close().

没有close它需要一段时间,直到缓冲区的内容到达文件.一旦不使用文件描述符,最好立即关闭文件描述符.

作为旁注,您可以使用以下语法糖来确保文件描述符尽快关闭:

with open(file, mode) as f:
    do_something_with(f)
Run Code Online (Sandbox Code Playgroud)

现在,关于覆盖部分:

写入文件而不覆盖以前的内容.

简短回答:您没有以正确的模式打开文件.使用追加模式("a").


答案很长:

这是预期的行为.阅读以下:

>>> 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.
Run Code Online (Sandbox Code Playgroud)

因此,阅读手册显示,如果您希望保留内容,则应以附加模式打开:

open(file, "a")
Run Code Online (Sandbox Code Playgroud)