只读 只写 追加
### 只读
# f= open ("models",mode="r",encoding="utf-8") # 第一个参数为 文件路径:分为相对路径和绝对路径,这里为相对路径;第二个为对文件袋的操作方式,第三个为编码
# content = f.read();
# print(content)
# f.close() #关闭流
# 以bytes 的形式 只读
# f= open( "models",'rb',)
# content =f.read()
# print(content)
# f.close()
### 只写 ,会先将文件的内容全部清除后,在写
# f=open("models",'w',encoding="utf-8")
# f.write("你过来呀w")
# f.close()
#
# f=open("models",'wb',)
# f.write("你过来呀wb".encode('utf-8'))
# f.close()
### 追加
# f = open("models",'a',encoding="utf-8")
# f.write("琪亚娜")
# f.close();
# f = open("models",'ab')
# f.write("琪亚娜".encode('utf-8'))
# f.close();
读写
### 读写
#r+
# f = open("models",mode="r+",encoding="utf-8")
# print(f.read())
# f.seek(0)
# f.write("起来")
#r+
# f = open("models",mode="r+b",)
# print(f.read())
# f.seek(0)
# f.write("起来".encode("utf-8"))
### 写读
# w+
# f = open("models",mode="w+",encoding="utf-8")
# # f.write("不用")
# # f.seek(0)
# # print(f.read())
# # f.close()
# w+b
# f = open("models",mode="w+b",)
# f.write("不用".encode("utf-8"))
# f.seek(0)
# print(f.read())
# f.close()
### 追加 读
# a+
f = open("models",mode="a+",encoding="utf-8")
f.write("仪器")
f.seek(0)
print(f.read())
f.close()
# a+b
f = open("models",mode="a+b",)
f.write("仪器".encode("utf-8"))
f.seek(0)
print(f.read())
f.close()
一些方法 的介绍
f = open("log","r+",encoding="utf-8")
# con = f.read(3) # 读取前3个字节
# print(con)
# f.seek(2) #按照字节定光标的位置
# print(f.tell()) #告诉你光标的位置
# f.readable() #是否可读
# line = f.readline() #一行一行的读
#lines = f.readlines() #每一行当成列表中的一个元素,添加到list中
# for lin in f:
# print(lin)
#f.truncate(4) #截断剩余的字符
with
with open('log',mode="r+",encoding="utf-8") as f1,open("log1","w+",encoding="utf-8") as f2:
list = f1.readlines()
for i in list:
print(i)
f1.write("你好")
f2.write("你过来啊")
# print(f2.readline())
利用文件完成登入功能
username = input('请输入你要注册的用户名:')
password = input('请输入你要注册的密码:')
with open('list_of_info',mode='w',encoding='utf-8') as f:
f.write('{}
{}'.format(username,password))
print('恭喜您,注册成功')
lis = []
i = 0
while i < 3:
usn = input('请输入你的用户名:')
pwd = input('请输入你的密码:')
with open('list_of_info',mode='r+',encoding='utf-8') as f1:
for line in f1:
lis.append(line)
if usn == lis[0].strip() and pwd == lis[1].strip():
print('登录成功')
break
else:print('账号和密码错误')
i+=1