文件操作
fp = open(“文件名”,mode=“模式”,encoding=“utf-8”)
fp - > 文件的io对象 (文件句柄)
i => input 输入
o => output 输出
1. 文件的写入
-
打开文件
fp = open("ceshi1.txt",mode="w",encoding="utf-8") # 把冰箱门打开
-
写入文件
fp.write("把大象放进去") # 把大象放进去
-
关闭文件
fp.close() # 把冰箱门关上
2. 文件的读取
-
打开文件
fp = open("ceshi1.txt",mode="r",encoding="utf-8") # 打开冰箱门
-
读取内容
res = fp.read() # 把大象拿出来 print(res)
-
关闭文件
fp.close() # 把冰箱门关上
3. 字节流的转换
bytes : 是用来传输或者存储的数据格式
b’1234’ b"abcd" b"我爱你" -> b开头的字节流,范围只能是ASCII编码
如果是中文,使用encode 和 decode 来进行转换
将字符串和字节流(Bytes流)类型进行转换 (参数写成转化的字符编码格式)
encode() 编码 : 将字符串转化为字节流(Bytes流)
decode() 解码: 将Bytes流转化为字符串
a = b'1234'
print(a , type(a))
strvar = "我爱你"
# encode 编码 -> 变成二进制字节流
res = strvar.encode("utf-8")
print(res , type(res))
# decode 解码 -> 二进制字节流恢复成原来的字符串
res2 = res.decode("utf-8")
print(res2 , type(res2))
# len 可以计算字节个数
num = len(res)
print(num) # 9
# 一个中文占用3个字节,通过decode 反解出'爱'这个字
res3 = b"\xe7\x88\xb1".decode("utf-8")
print(res3)
# 程序员的表白方式
strvar = "我!是你一辈子也得不到的男人"
strvar2 = strvar.encode("utf-8")
print(strvar2)
4. 存储二进制字节流
"""不需要指定encoding编码集,否则报错"""
fp = open("ceshi2.txt",mode="wb")
fp.write(strvar2)
fp.close()
5. 读取二进制字节流
fp = open("ceshi2.txt",mode="rb")
res = fp.read()
fp.close()
print(res)
# 通过decode反解出字符串
strvar = res.decode()
print(strvar)
6. 复制图片
# 1. 读取原图片所有的内容
fp = open("集合.png",mode="rb")
res = fp.read()
fp.close
# 2. 把读取的内容存储到另外一个文件
fp = open("集合2.png",mode="wb")
fp.write(res)
fp.close()
# 3. 指定绝对路径(完整路径)
fp = open(r"E:\python31\day8\集合3.png",mode="wb")
fp.write(res)
fp.close()
7.文件的扩展模式
utf-8 编码格式下 默认一个中文占用三个字节,一个英文或者符号占用一个字节
read() 功能: 读取字符的个数 (里面的参数代表字符个数)
seek() 功能: 调整指针的位置 (里面的参数代表字节个数)
seek(0) 直接把光标移动到文件开头
seek(0,2) 直接把光标移动到文件末尾
tell() 功能: 当前光标左侧所有的字节数 (返回字节数)
-
r+ 先读后写
fp = open("ceshi3.txt",mode="r+",encoding="utf-8") # 先读 res = fp.read() print(res) # 后写 fp.write("1234") # 再读 fp.seek(0) # 调整光标位置在开头 res = fp.read() print(res) fp.close()
-
r+ 先写后读
fp = open("ceshi3.txt",mode="r+",encoding="utf-8") fp.seek(0,2) # 调整光标位置在末尾 fp.write("123") fp.seek(0) res = fp.read() print(res) fp.close()
-
w+ 可读可写
fp = open("ceshi4.txt",mode="w+",encoding="utf-8") fp.write("abcd") fp.seek(0) res = fp.read() print(res) fp.close()
-
a+ 可读可写
"""文件不存在时,默认创建新的文件""" fp = open("ceshi5.txt",mode="a+",encoding="utf-8") fp.write("123") fp.seek(0) res = fp.read() print(res) """a模式在写入内容时,会强制把光标移动到最后""" fp.seek(1) fp.write("abc") fp.close() """如果在r模式内,区别a模式""" fp = open("ceshi5.txt",mode="r+",encoding="utf-8") fp.seek(1) fp.write("abc") fp.close()
8. read seek tell 三个函数的使用
fp = open("ceshi6.txt",mode="r+",encoding="utf-8")
res = fp.read(3)
print(res)
fp.seek(6)
print(fp.read(1))
# 计算文件指针左侧所有的字节数
res = fp.tell()
print(res)
fp.close()
# 注意点: seek 移动中文字节的时候,有可能报错
fp = open("ceshi6.txt",mode="r+",encoding="utf-8")
fp.seek(2)
res = fp.read()
print(res)
fp.close()
# print("我".encode()) => b'\xe6\x88\x91'
9. with语法的使用 (close操作=>with语法可以自动实现)
with open("集合.png",mode="rb") as fp:
res = fp.read()
with open(r"E:\python31\day8\集合4.png",mode="wb") as fp:
fp.write(res)
# 继续优化 合并with
with open("集合.png",mode="rb") as fp1 , open(r"E:\python31\day8\集合4.png",mode="wb") as fp2:
res = fp1.read()
fp2.write(res)
10. close 文件关闭的意义
刷新缓冲区 flush
当文件关闭时自动刷新缓冲区
当整个程序运行结束时自动刷新缓冲区
当缓冲区写满了会自动刷新缓冲区
手动刷新缓冲区
fp = open("ceshi6.txt",mode="r+",encoding="utf-8")
fp.write("zzz")
# 手动把缓冲区里面的内容写入文件当中
fp.flush()
while True:
pass
fp.close()
11. 文件的相关函数
-
readable() 判断文件对象是否可读
fp = open("ceshi6.txt",mode="a+",encoding="utf-8") res = fp.readable() print(res)
-
writable() 判断文件对象是否可写
res = fp.writable() print(res)
-
readline() 读取一行内容
""" 参数 > 当前行字符总个数 => 以当前行读取 参数 < 当前行字符总个数 => 以参数的大小来读取字符的个数 默认readline 读取一行 """ with open("ceshi7.txt",mode="r+",encoding="utf-8") as fp: # 方式一 res = fp.readline(30) print(res) # 方式二 # 文件对象 fp 也是一个可迭代对象 # 在遍历文件对象时,默认一次拿一行 for i in fp: print(i) # 读取所有内容 while open("ceshi7.txt",mode="r+",encoding="utf-8") as fp: # 先读取一行 res = fp.readline() # 判断是不是空 while res: print(res) res = fp.readline()
-
readlines() 将文件中的内容按照换行读取到列表当中
lst_new = [] with open("ceshi7.txt",mode="r+",encoding="utf-8") as fp: lst = fp.readlines() # print(lst) # ['\t窗前明月光\n', '疑是鞋两双\t\t\n', '\t\t举头王明月\n', '\t低头看裤裆'] for i in lst: lst_new.append(i.strip()) print(lst_new) # ['窗前明月光', '疑是鞋两双', '举头王明月', '低头看裤裆']
-
writelines() 将内容是字符串的可迭代型数据写入文件中,参数: 内容为字符串类型的可迭代数据
"""可迭代型数据 => 容器类型数据 range对象 迭代器""" lst = ["春眠不觉晓\n","处处蚊子咬\n","夜来大狗熊\n","一个也跑不了\n"] # lst=[1,2,3,4] error with open("ceshi8.txt",mode="w",encoding="utf-8") as fp: fp.writelines(lst)
-
truncate() 把要截取的字符串提取出来,然后情况内容将提取的字符串重新写入文件中
with open("ceshi8.txt",mode="r+",encoding="utf-8") as fp: fp.truncate(3) while " ": print(123)
练习
练习1
1.有如下文件,a1.txt,里面的内容为:
键盘敲烂,
月薪过万.
键盘落灰,
狗屎一堆.
分别完成以下的功能:
a:将原文件全部读出来并打印。
with open("a1.txt",mode="r+",encoding="utf-8") as fp:
res = fp.read()
print(res)
b:在原文件后面追加一行内容:信不信由你,反正我信了。
with open("a1.txt",mode="r+",encoding="utf-8") as fp:
fp.write("\n\t信不信由你,反正我信了")
c:将原文件全部读出来,并在后面添加一行内容:信不信由你,反正我信了。
with open("a1.txt",mode="a+",encoding="utf-8") as fp:
fp.seek(0)
res = fp.read()
fp.write("\n\t信不信由你,反正我信了")
d:将原文件全部清空,换成下面的内容:
每天坚持一点,
每天努力一点,
每天多思考一点,
慢慢你会发现,
你的进步越来越大。
strvar = """
每天坚持一点,
每天努力一点,
每天多思考一点,
慢慢你会发现,
你的进步越来越大。
"""
with open("a1.txt",mode="w+",encoding="utf-8") as fp:
fp.write(strvar)
e:将原文件内容全部读取出来,
并在’键盘落灰’这一行的前面加一行,‘年薪百万’
然后将更改之后的新内容,写入到一个新文件:a2.txt
with open("a1.txt",mode="r+",encoding="utf-8") as fp1,open("a2.txt",mode="w+",encoding="utf-8") as fp2:
lst = fp1.readlines()
print(lst)
lst.insert(2,"\t年薪百万,\n")
fp2.writelines(lst)
练习2
2.有如下文件,t1.txt,里面的内容为:
葫芦娃,葫芦娃,
一根藤上七个瓜
风吹雨打,都不怕,
啦啦啦啦。
上面的内容你肯定是心里默唱出来的,对不对
分别完成下面的功能:
a:以r+的模式打开原文件,判断原文件是否可读,是否可写。
fp = open("t1.txt",mode="r+",encoding="utf-8"):
print(fp.readable())
print(fp.writable())
fp.close()
b:以r的模式打开原文件,利用for循环遍历文件对象。
with open("t1.txt",mode="r",encoding="utf-8") as fp:
for i in fp:
print(i.strip())
c:以r的模式打开原文件,以readlines()方法读取出来,并循环遍历
with open("t1.txt",mode="r",encoding="utf-8") as fp:
lst = fp.readlines()
for i in lst:
print(i)
d:以r模式读取‘葫芦娃,’前四个字符。
"""
在r 模式下,read读取的是字符
在rb模式下,read读取的是字节
"""
with open("t1.txt",mode="r",encoding="utf-8") as fp:
res = fp.read(4)
print(res)
with open("t1.txt",mode="rb") as fp:
res = fp.read(12)
print(res.decode())
e:以r模式读取第一行内容,并去除此行前后的空格,制表符,换行符。
with open("t1.txt",mode="r",encoding="utf-8") as fp:
res = fp.readline()
print(res.strip())
f:以r模式打开文件,从‘风吹雨打…’开始读取,一直读到最后。
with open("t1.txt",mode="r",encoding="utf-8") as fp:
lst = fp.readlines()
print(lst)
print(lst[2:])
for i in lst[2:]:
print(i)
g:以a+模式打开文件,先追加一行:‘老男孩教育’然后在全部读取出来。
with open("t1.txt",mode="a+",encoding="utf-8") as fp:
fp.write("\n\t老男孩教育")
fp.seek(0)
print(fp.read())
h:截取原文件,截取内容:‘葫芦娃,葫芦娃,’
with open("t1.txt",mode="r",encoding="utf-8") as fp:
fp.truncate(24)
练习3
3.文件a.txt内容:每一行内容分别为商品名字,价钱,个数。
apple 10 3
tesla 100000 1
mac 3000 2
lenovo 30000 3
chicken 10 3
变成如下数据格式,并计算出总价格
[
{‘name’:‘apple’,‘price’:10,‘amount’:3},
{‘name’:‘tesla’,‘price’:1000000,‘amount’:1}
]
lst_new = []
total = 0
with open("a.txt",mode="r+",encoding="utf-8") as fp:
lst = fp.readlines()
print(lst)
for i in lst:
dic = {}
name,price,amount = i.strip().split()
dic["name"] = name
dic["price"] = float(price)
dic["amount"] = float(amount)
lst_new.append(dic)
total += dic["price"] * dic["amount"]
print(lst_new)
print(total)