如何在Python中安全地打开/关闭文件?
open()打开一个文件。您可以像这样使用它:
f = open('my_file', 'r+')
my_file_data = f.read()
f.close()上面的代码在读取模式下打开“my_file”,然后将从my_file读取的数据存储在my_file_data中并关闭文件。open的第一个参数是文件的名称,第二个参数是打开模式。它确定如何打开文件。
例如
– If you want to read the file, pass in r – If you want to read and write the file, pass in r+ – If you want to overwrite the file, pass in w – If you want to append to the file, pass in a
当您打开文件时,操作系统会提供一个文件句柄来读取/写入文件。使用完文件后,需要关闭它。如果您的程序遇到错误并且没有调用f.close(),则您没有释放文件。为了确保它不会发生,您可以将open(...)用作f语法,因为它会自动关闭文件,而不管是否遇到错误:
with open('my_file', 'r+') as f:
my_file_data = f.read()热门推荐
1 狗狗技能训练
5 如何训练狗狗笑
6 狗狗训练排便
9 狗狗响片训练
10 如何训练狗狗不捡食
11 狗狗尿训练
12 怎么训练狗狗找东西
13 狗狗训练站立
14 狗狗训练飞盘
15 鞍山狗狗训练
16 怎样训练泰迪狗狗谢谢
17 狗狗外出训练
18 怎么训练金毛狗狗大小便