繁体   English   中英

我无法在 Python 3.9 代码中读取/写入文件

[英]I can't read/write a file in my Python 3.9 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()

我把“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”的内容没有被删除。 然后我尝试将模式更改为“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()读取整个文件并将当前 position 留在文件末尾,因此第二次f.read()调用从文件末尾开始并且不读取任何内容。 相反,将读取的内容保存到变量中。

另外, w+会先截断文件,使用r+可以避免这种情况。

我还假设您要清除文件中的先前值,因此使用f.truncate清除文件并使用 f.seek 将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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM