Python with as 读写文件详解

1 概述

  • "传统方法": 读写文件时,总是要写关闭语句,不但容易忘记,而且写法也比较 繁琐
  • "with open() as 方法" :实现的功能相同,但语句更加 简洁

2 详解

2.1 区别

2.1.1 传统方法

path = r"C:\Users\wangyou\Desktop\1"

full_file_name = path + r'\1.txt'

file = open(full_file_name, 'r')
try:
    file_content = file.read()
    print(file_content)
finally:
    file.close()

2.1.2 with open() as 方法

  • 与上述 “传统方法” 完全一致(异常时,自动关闭文件)
path = r"C:\Users\wangyou\Desktop\1"

full_file_name = path + r'\1.txt'

with open(full_file_name, 'r') as file:  # 自定义名称,如:file
    print(file.read())

2.2 with open() as 原理

  • 基本思想是 with 所求值的对象必须有一个 enter() 方法,一个 exit() 方法。
  • enter() : 该方法的返回值被赋值给 as 后面的变量
  • exit() : 当 with 后面的代码块全部被执行完之后,再执行该方法(如:file.close())

建议 Debug 下列代码:

class Sample:
    def __enter__(self):
        print("In __enter__()")
        return "Foo"

    def __exit__(self, type, value, trace):
        print("In __exit__()")


def get_sample():
    return Sample()


if __name__ == '__main__':
    with get_sample() as sample:
        print("sample:", sample)

测试结果:

In __enter__()
sample: Foo
In __exit__()

3 示例

def write_file(path):
    with open(path, 'w', encoding='utf-8') as file:  # 'a': 追加
        file.write("Hello, Python!")


def read_file(path):
    with open(path, 'r', encoding='utf-8') as file:
        print(file.read())


if __name__ == '__main__':
    path = r"C:\Users\wangyou\Desktop\1"

    full_file_name = path + r'\1.txt'

    write_file(full_file_name)
    read_file(full_file_name)

猜你喜欢

转载自blog.csdn.net/qq_34745941/article/details/108669264