问题描述
with open("count.txt","w+") as f:
print(f.read())
a=int(f.read())
b=int(a+1)
print(str(b))
f.write(str(b))
input()
我把“count.txt”放在同一个目录下,这是“count.txt”的内容
0
这是我得到的错误:
Traceback (most recent call last):
File "C:\FILEDIRECTORY\plus.py",line 3,in <module>
a=int(f.read())
ValueError: invalid literal for int() with base 10: ''
然后,“count.txt”变为空白(0 字节)。 我试图将模式更改为“r”,但发生了同样的错误,但“count.txt”的内容没有被删除。然后我试着把mode改成“w”,把f.write的内容改成“1”,把其他代码注释掉。
with open("count.txt","w") as f:
'''print(f.read())
a=int(f.read())
b=int(a+1)
print(str(b))'''
f.write("1")
input()
但现在它起作用了! “count.txt”内容变为“1”! 我也试试这个:
with open("count.txt","w") as f:
'''print(f.read())
a=int(f.read())
b=int(a+1)
print(str(b))'''
a="1"
f.write(a)
input()
它仍然有效! 所以我认为阅读模式坏了,但我不知道为什么。 也许我安装的 Python 不正确?
解决方法
f.read()
读取整个文件并将当前位置留在文件末尾,因此第二个 f.read()
调用从文件末尾开始并且不读取任何内容。相反,将读取的内容保存到变量中。
此外,w+
会先截断文件,使用 r+
可以避免这种情况。
我还假设您要清除文件中的先前值,因此使用 f.truncate
清除文件并使用 f.seek
将位置重置为文件开头。>
综合起来:
with open("count.txt","r+") as f:
content = f.read()
print(content)
a = int(content)
b = a+1
print(b)
f.truncate(0)
f.seek(0)
f.write(str(b))
input()