一、文件操作流程
1、文件操作流程
- 打开文件,得到一个文件对象并赋值给一个变量(应用程序本质是给操作系统发送打开文件的请求)
- 通过变量对文件进行操作(给操作系统发送该请求对文件进行操作)
- 关闭文件,回收系统资源(给操作系统发送关闭文件的请求)
二、文件操作方法
1、open
f=open("file",'r',encoding='utf-8')
print(f.read())
f.close()
注:每次都需要手工关闭,很麻烦,可不可以不需要手工关闭呢
2、with open
with open("file",'r',encoding='utf-8') as f:
print(f.read())
注:with open通过缩进自动关闭文件
3、打开文件时指定字符编码
encoding='utf-8'
注意:
- 只有文本文件才涉及到字符编码,如果是图片或者视频,不需要指定字符编码,因为那是二进制文件
- encoding指定的字符编码一定要跟文件存的时候用的编码一致
- 不指定encoding默认使用操作系统默认的编码,Windows默认是GBK,Linux是UTF-8
三、对文件对象的操作方法
1、读取
读取所有内容,返回字符串
with open('a.txt','r',encoding='utf-8') as f:
data=f.read()
print(data,type(data))
#返回值
jesus loves you
jesus loves you
jesus loves you <class 'str'>
读取一行内容,返回字符串
with open('a.txt','r',encoding='utf-8') as f:
data=f.readline()
print(data,type(data))
#返回值
jesus loves you
<class 'str'>
读取所有,返回列表
with open('a.txt','r',encoding='utf-8') as f:
data=f.readlines()
print(data,type(data))
#返回值
['jesus loves you\n', 'jesus loves you\n', 'jesus loves you'] <class 'list'>
2、写入
写入单行文件
with open('b.txt',mode='w',encoding='utf-8') as f:
f.write('hello world\n')
#内容
hello world
写入列表,相当于for循环写入
with open('b.txt',mode='w',encoding='utf-8') as f:
f.writelines(['a\n','b\n'])
#内容
a
b