简体   繁体   中英

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"

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). I tried to change the mode to "r", but the same error happen, but the content of "count.txt" doesn't get erased. Then I try to change the mode to "w", change the f.write content to "1", and make the other code comment.

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"! 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?

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. Instead, save the read content to a variable.

In addition, w+ truncates the file first, use r+ to avoid this.

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.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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