def new_op_file(filename,content=None): f = open(filename,'a+') f.seek(0) if content: #非空即真,如果有内容就往下运行 f.truncate()#清空文件 f.write(str(content))#write只能写入字符串,所以需要转化为str res = ''#写入操作,所以返回是空 else: res = eval(f.read())#将读到的字符串转化为原来的数据格式 f.close() return res print(new_op_file('day51.txt','hhhaaaa'))