[英]I can't read/write a file in my Python 3.9 code
I don't know what happen, but my code doesn't want to work properly.我不知道会发生什么,但我的代码不想正常工作。 This is the code:
这是代码:
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()
I put the "count.txt" in same directory, and this is the content of "count.txt"我把“count.txt”放在同一个目录下,这就是“count.txt”的内容
0
and this is the error that I got:这是我得到的错误:
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: ''
Then, the "count.txt" become blank (0 bytes).然后,“count.txt”变为空白(0 字节)。 I tried to change the mode to "r", but the same error happen, but the content of "count.txt" doesn't get erased.
我试图将模式更改为“r”,但发生了同样的错误,但“count.txt”的内容没有被删除。 Then I try to change the mode to "w", change the f.write content to "1", and make the other code comment.
然后我尝试将模式更改为“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()
But now it works.但现在它起作用了。 The "count:txt" content become "1"!
“count:txt”的内容变成了“1”! I also try this :
我也试试这个:
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()
And it still works, So i think the read mode is broken.它仍然有效,所以我认为读取模式已损坏。 but i don't know why?
但我不知道为什么? Maybe I Install Python Incorrectly?
也许我安装 Python 不正确?
f.read()
reads the entire file and leaves the current position at the end of the file, so the 2nd f.read()
call starts from the end of the file and doesn't read anything. f.read()
读取整个文件并将当前 position 留在文件末尾,因此第二次f.read()
调用从文件末尾开始并且不读取任何内容。 Instead, save the read content to a variable.相反,将读取的内容保存到变量中。
In addition, w+
truncates the file first, use r+
to avoid this.另外,
w+
会先截断文件,使用r+
可以避免这种情况。
I'm also assuming that you want to clear the previous value in the file, so use f.truncate
to clear the file and f.seek
to reset the position to the start of the file.我还假设您要清除文件中的先前值,因此使用
f.truncate
清除文件并使用 f.seek 将f.seek
重置为文件的开头。
Putting it all together:把它们放在一起:
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.