五 with +open形式读写文件

BUG之神 47

with open()语句是一种更加简洁和安全的文件操作方式。它会在文件使用完毕后自动关闭文件,无需显式调用close()函数。下面是语法示例:

with open(file, 'mode') as f:

with open()语句的各种模式与open()语句一样,这里不做赘述。

使用示例

写入文件

with open("E:/demo1.txt",'w',encoding='utf-8') as file:
    file.write("111")

五 with +open形式读写文件 

读取文件

with open("E:/demo1.txt",'r',encoding='utf-8') as file:
    text=file.read()
    print(text)

五 with +open形式读写文件 

 

同时打开多个文件

先创建两个文本文件,内容如下:

五 with +open形式读写文件 

 

with open('E:/test1.txt', 'r', encoding='utf-8')as f1, open('E:/test2.txt', 'r', encoding='utf-8')as f2:
    print(f1.read())
    print(f2.read())

五 with +open形式读写文件 

注:为了避免文件打开时出现UnicodeDecodeError建议在打开文件时,加上encoding='utf-8'参数。

异同点与最优选择参考:https://zhuanlan.zhihu.com/p/651164033

open()函数与os.open()函数不会自动关闭文件,需要调用close方法,这一点是with open()的大优势,不会造成资源泄漏的问题。

使用open()函数和with open()语句是进行文件操作的常见做法,尤其是对于简单的文件读写任务。

需要以低级别方式操作文件时,才使用os.open()函数,它更适用于特定的场景,如需要在文件中定位和读取特定位置的数据。

在使用with open()语句时,可以在语句块中进行其他的文件操作,例如写入内容或定位文件指针位置。

综合来说,执行文件操作时,最优选择毫无疑问是with open(),建议执行文件操作时使用’with open()'语句!!!

  

分享