Weird behavior when writing and reading file

前端 未结 2 1694
时光说笑
时光说笑 2021-01-15 10:45

When executing the following code, after the second read, file gets filled with zero until being 4096 bytes large. I can\'t figure out why :

f = open(\"file.         


        
2条回答
  •  轮回少年
    2021-01-15 11:30

    Best way to solve your problem: don't mix read() and write().

    Otherwise: after the write(), use seek() before the second read() to read your file from the beginning:

    f = open("file.txt", "w+")
    print f.read()      # prints ''
    f.write("Hello")
    f.seek(0)
    print f.read()      # print 'Hello'
    f.close()
    

提交回复
热议问题