# 值互换
a = 10
b = 20
# temp = a
# a = b
# b = temp
a, b = b, a # 这样也可以
print(a, b) # a=20, b=10
文件操作
f = open("海贼王.txt", mode="r", encoding="utf-8")
content = f.read()
print(content)
print(f.readline().strip()) # 一行一行读
# print(f.readline(), end="") #也可以去除换行
print(f.readline())
print(f.readlines())
for i in f: # 从文本中读取每一行数据
print(i.strip())
print("--------------------------------------------")
# 写入文件
f = open("EVA.txt", mode="w", encoding="utf-8")
# w模式下,若文件不存在,会自动创建
# w模式下,每次open都会清空文件中的内容!!!!!
f.write("明日香")
f.close() # 每次操作之后记得关闭链接
print("==========================")
# 把列表中的元素逐个写入文件
lst = ["初号机", "二号机", "零号机"]
f = open("打使徒.txt", mode="w", encoding="utf-8")
for i in lst:
f.write(i)
f.write("\n")
f.close()
print("--------------------------------------------")
# 追加内容,不会像w模式一样每次打开清空内容
f = open("动漫.txt", mode="a", encoding="utf-8")
f.write("海贼王")
f.write("EVA")
f.close()
print("--------------------------------------------")
with open("海贼王.txt", mode="r", encoding="utf-8") as f: # 上下文管理器,会自动close文件
for i in f:
print(i.strip())
# 文件复制
with open("二次元.jpg", mode="rb") as f1, \
open("../复制路径/二次元2.jpg", mode="wb") as f2:
for i in f1:
f2.write(i)
# \的作用是表示 下面和上面是同一行代码,没有\会报错
print("--------------------------------------------")
# 文件修改
with open("名单.txt", mode="r", encoding="utf-8") as f1, \
open("名单new.txt", mode="w", encoding="utf-8") as f2:
for i in f1:
i = i.strip() # 去除换行
if i.startswith("周"):
i = i.replace("周", "张")
f2.write(i)
f2.write("\n")
# 删除源文件
os.remove("名单.txt")
# 把副本文件重命名成源文件
os.rename("名单new.txt", "名单.txt")