保存在内存中的变量在程序关闭之后将被释放,为了长期保存相关信息,需要将数据保存在本地文件或者数据库中。本文主要介绍文件的读写
流程
针对文件的操作都需要打开、操作(读写)、关闭三个步骤

语法
f = open('/home/python/python_file',‘r’)
#以只读模式打开文件/home/python/python_file
#r为只读,若文件不存在则报错;w为写默认会清空当前内容,若文件不存在则创建;x为创建一个新文件,若已存在则报错;a为追加,在文件末尾追加内容
f.read()
f.readline()
f.readlines()
#以上三个都是读操作
#read()一次性读取所有内容
#readline()每次读取一行
#readlines()一次性读取所有内容,并将结果保存在列表中
#read()、readlines()都需要加载所有内容到内存中,需考虑内存溢出情况
f.write("需输入的内容")
f.wirtelines(['需输入的内容1',‘需输入的内容2’,'需输入的内容3'])
#以上两个操作都是写操作
#write()写入字符串并返回字符数
#writelines()写入字符串列表
f.close()
#关闭文件
案例
1 读文件
读取文件内容需要先打开文件、然后进行读操作、最后关闭文件避免文件句柄泄露
[root@LINCB python]# cat python_file
hello_python_01
#linux下获取文件信息
>>> f = open('/home/python/python_file')
>>> print(f.read())
hello_python_01
hello_python_02
hello_python_03
>>> f.close()
#read一次性读取文档中所有内容
>>> f = open('/home/python/python_file')
>>> print(f.readline())
hello_python_01
>>> print(f.readline())
hello_python_02
>>> print(f.readline())
hello_python_03
>>> f.close()
#readline每次读取一行
>>> f = open('/home/python/python_file')
>>> print(f.readlines())
['hello_python_01\n', 'hello_python_02\n', 'hello_python_03\n']
>>> f.close()
#readlines将结果存在一个列表中,可使用for遍历操作
#read和readlines都需要一次性将文档中所有内容加载到内存中,需要考虑内存溢出的可能性
2 写文件
写操作需要注意文件打开模式,r为只读,若文件不存在则报错;w为写默认会清空当前内容,若文件不存在则创建;x为创建一个新文件,若已存在则报错;a为追加,在文件末尾追加内容
[root@LINCB python]# cat python_file
hello_python_01
#初始文件
>>> f = open('/home/python/python_file','a')
>>> f.writelines(['hello_python_04\n','hello_python_05\n'])
>>> f.close()
#追加模式下使用writelines()添加两行字符串
[root@LINCB python]# cat python_file
hello_python_01
hello_python_04
hello_python_05
#在文档最后新增
>>> f = open('/home/python/python_file','w')
>>> f.write('hello_python_04\n')
16
>>> f.close()
#编辑模式下使用write添加字符串
[root@LINCB python]# cat python_file
hello_python_04
#文档原有内容已被清空
3 文件关闭
打开一个文件就会创建一个句柄,系统中句柄的数量有限制,且会消耗资源;为避免没有及时文件导致文件句柄泄露,这边介绍两种方法。
>>> try:
... f = open('/home/python/python_file','w')
... f.write('hello_python_04\n')
... finally:
... f.close()
16
#使用finally语句来保证,无论什么情况下文件都会被关闭
>>> with open('/home/python/python_file') as f:
... print(f.read())
hello_python_04
#使用上下文管理器来实现如上目标
文章转载自lin在路上,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




