慕仰8121524
假设您正在用with像你应该说的那样。然后你会做这样的事情来阅读你的文件:withopen('somefile.txt','w+')asf:
#Notethatfhasnowbeentruncatedto0bytes,soyou'llonly
#beabletoreaddatathatyouwriteafterthispoint
f.write('somedata\n')
f.seek(0)#Important:returntothetopofthefilebeforereading,otherwiseyou'lljustreadanemptystring
data=f.read()#Returns'somedata\n'注意f.seek(0)-如果你忘了这件事,f.read()调用将尝试从文件末尾读取,并返回一个空字符串。