假设你要打开的文件带有
with应有的声明。然后,你将执行以下操作以从文件中读取内容:
with open('somefile.txt', 'w+') as f: # Note that f has now been truncated to 0 bytes, so you'll only # be able to read data that you write after this point f.write('somedatan') f.seek(0) # important: return to the top of the file before reading, otherwise you'll just read an empty string data = f.read() # Returns 'somedatan'请注意
f.seek(0)-如果你忘记了这一点,则该
f.read()调用将尝试从文件末尾读取,并将返回一个空字符串。



