# 一次行读取文件所有内容
f = open("d:/a.txt", mode="r", encoding="utf-8")
c = f.read()
print(c)
f.close()
"""如果文件太大,可以一行一行的读取"""
f = open("d:/a.txt", mode="r", encoding="utf-8")
l = f.readline() # 读取一行
print(l.strip())
l = f.readline() # 读取一行
print(l.strip())
f.close()
# 循环读取文件
f = open("d:/a.txt", mode="r", encoding="utf-8")
for l in f:
print(l.strip())
f.close()
"""
mode = "w" 文件不存在就创建,如果存在就覆盖
"""
f = open("b.txt", mode="w", encoding="utf-8")
f.write("大家好\n")
f.write("我叫\n")
f.write("xxxx\n")
f.close()
lst = ["张三", "李四0", "王五"]
f = open("b.txt", mode="w", encoding="utf-8")
for item in lst:
f.write(item)
f.write("\n")
print("over")
f.close()
"""追加内容到文件的后面,model="a" append追加"""
f = open("c.txt", mode="a", encoding="utf-8")
lst = ["张三", "李四0", "王五"]
for item in lst:
f.write(item)
f.write("\n")
print("over")
f.close()
"""with 关键字来创建文件,在结束后会自动关闭文件"""
with open("c.txt", mode="a", encoding="utf-8") as f:
f.write("追加的内容")
f.write("\n")
print("over")
"""复制文件,c.txt 复制到 d.txt"""
with open("c.txt", mode="r", encoding="utf-8") as f1,\
open("d:/d.txt", mode="w", encoding="utf-8") as f2:
for line in f1:
f2.write(line)
print("over")
"""读取二进制文件,model = "rb" 读写二进制文件,就不要加编码格式"""
with open("a.png", mode="rb") as f:
for l in f:
print(l)
with open("a.png", mode="rb") as f1,\
open("b.png", mode="wb") as f2:
for l in f1:
f2.write(l)
print("over")
"""
修改文本文件:
1. 读取a.txt文件,将修改后的内容写入a_back.txt副本(新的文件)
2. 删除a.txt文件
3. 将 a_back.txt 重新命名为 a.txt
"""
import os
import time
with open("a.txt", mode="r", encoding="utf-8") as f1,\
open("a_back.txt", mode="w", encoding="utf-8") as f2:
for l in f1:
if l.startswith("张"):
l = "李"+l[1:]
f2.write(l)
time.sleep(2)
# 2 删除a.txt
os.remove("a.txt")
time.sleep(2)
# 3.重命名
os.rename("a_back.txt", "a.txt")
time.sleep(2)
print("over")