一、打开文件
open(file,mode='r',encoding=None) -以指定的模式打开指定文件并返回一个文件对象
说明:file - 文件路径,字符串类型
绝对路径:文件/文件夹的全路径(一般不写绝对路径)
相对路径:只写文件绝对路径的一部分,另外一部分用特殊符号代替
./ - 表示当前目录(可以省略)
mode - 打开方式,字符串类型
第一组:控制操作类型
r - 以只读的方式打开文件(默认值)
w - 以只写的方式打开文件(打开前先清空原文件的内容)
a - 以只写的方式打开文件(打开前不会清空原文件的内容)
第二组:控制数据类型(文本-str/二进制数据-bytes)
t - 操作的数据是文本数据(默认)
b - 操作的数据是二进制数据
注意:每一组值只选一个,两组值进行组合使用
encoding = 'utf-8'
注意:如果打开方式带b,不能设置encoding
总结:文本文件打开的时候可以是t也可以是b,二进制文件只能是b打开(图片文件,音频、视频等)
二、打开方式
方式一:
文件对象 = open(文件路径,文件打开方式,encoding=文件编码方式)
操作文件对象
文件对象.close()
方式二:
with open(文件路径,文件打开方式,encoding=文件编码方式)as 文件对象:
操作文件对象
三、文件操作
1、文件读操作
1)文件对象.read() - 从文件读写位置开始,读到文件结尾。(默认情况下读写位置在文件开头)
2)文件对象.readline() - 读文本文件的一行内容(从当前读写位置读到一行结束)
3)文件对象.readlines() - 一行一行的读,读完为止,返回的是一个列表,列表中的元素是列表中每一行的值
# 练习:一行一行读,读完为止
def read_file(file):
with open(file,'r',encoding='utf-8')as f:
while True:
contend = f.readline()
if not contend:
break
print(contend)
read_file('text')
2、文件写操作
文件对象.write(内容)
数据持久化的基本操作
1.数据保存在文件中
2.需要数据的时候从文件中去读数据
3.当数据发生改变的时候,对保存数据的文件进行更新
如果以读的方式打开一个不存在的文件,程序会报错;如果以写的方式打开一个不存在的文件,不会报错并新建该名字文件
# 练习写一个程序统计程序的启动次数
with open('text1','r',encoding='utf-8')as f:
count =int(f.read())
count += 1
print(count)
with open('text1','w',encoding='utf-8')as f:
f.write(str(count))
# 写程序实现添加学生的功能,要求每次运行程序添加的学生,下次还在
def add_stu():
while True:
name = input('输入姓名:')
with open('text1','a',encoding='utf-8')as f:
f.write('\nname:')
f.write(name)
with open('text1','r',encoding='utf-8')as f:
print(f.read())
add_stu()
names = ['张三','李四']
students = [
{'name':'张三','age':18},
{'name':'张三','age':18},
{'name':'张三','age':18},
{'name':'张三','age':18},
]
# 1.字典和列表的写操作:先将字典或列表转换成字符串
with open('text2','w',encoding='utf-8')as f:
f.write(str(students))
# 2.字典和列表的读操作:将容器格式的字符串转换成对应的容器型数据类型
with open('text2','r',encoding='utf-8')as f:
content = f.read()
print(content)
new_content = eval(content)
print(new_content)
for item in new_content:
print(item)
print(type(item))
def add_student():
while True:
name = input('姓名')
age = input('年龄')
tel = input('电话')
students = {'name':name,'age':age,'tel':tel}
with open('students','r',encoding='utf-8')as f:
all_students = eval(f.read())
all_students.append(students)
with open('students','w',encoding='utf-8')as f:
f.write(str(all_students))
print(all_students)
add_student()