''' 第二行添加hello world ''' res = f.readlines() for i in range(len(res)): # print(res[i]) if i == 1 : print(res[i].strip(),'hello world') else: print(res[i])
''' f.close()-->关闭文件 ''' # import time # f = open('test6.txt','w') # f.write("hello world") # time.sleep(5) #程序执行完毕才写入 # f.close()
# try: # f = open('test6.txt','w') # f.read() # except Exception as e: # print(e) # finally: # if f: # f.close()
''' 上下文管理器 with 自动调用__enter__(), 将方法的返回值给as后面的变量 相当于 f = open() with后面的代码块全部执行完毕之后,将调用前面返回对象__exit__() --> f.close() ''' with open('test8.txt','w') as f: f.write('hello world')