上下文管理器学习与简单的文件复制

# =====================上下文管理器========================================
'''
既然文件一定要及时关闭,是否能够让Python自动执行这个关闭过程,上下文管理器可以完成自动关闭文件。
能否同时管理多个文件的自动关闭
'''
with open (r"D:\s14\day1\test_doc.py","r+") as file:
    #代表用上下文管理器打开一个文件
    file.write("print(222)")

# 有多个文件时如何处理呢
with open(file.path,mode="r") as f1,\
    open(file.path,mode="r") as f2,\
    ...:

#-----------使用上下文管理器完成简单的文件复制---------------------------
def copy_file(old_file,new_file):
    with open(old_file) as old,\
        open(new_file,"w") as new:
        content = old.read()
        new.write(content)
        print("已经复制完成")
copy_file(r"D:\s14\day1\new_dir\test.txt","new.py")

猜你喜欢

转载自www.cnblogs.com/jb9527/p/10656741.html
今日推荐