写入和读取文件时的奇怪行为 [英] Weird behavior when writing and reading file
本文介绍了写入和读取文件时的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当执行以下代码时,在第二次读取后,文件被零填充,直到达到 4096 字节大.我不明白为什么:
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.txt", "w+")
f.read()
# gives ''
f.write("Hello")
f.read()
# filled with \x00,\x00
f.close()
# file is 4096 bytes large...
推荐答案
解决问题的最佳方式:不要混合使用 read()
和 write()
.
Best way to solve your problem: don't mix read()
and write()
.
否则:在 write()
之后,在第二个 read()
之前使用 seek()
来读取您的文件 开始:
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()
这篇关于写入和读取文件时的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文