python—文件创建

时间:2024-04-21 15:34:04
# 1、文件操作
# day1.txt
# 1、文件路径:E:\day1.txt
# 2、编码方式:utf-8、gbk
# 3、操作方式:只读,只写,追加,读写,写读
# 以什么编码方式储存的方式储存就以什么编码方式打开 #绝对路径
# f = open("E:\day1.txt",mode="r",encoding="gbk")
# count = f.read()
# print(count)
# f.close() #相对路径
# f = open("今天天气真好",mode="r",encoding="utf-8")
# count = f.read()
# print(count,type(count))
# f.close() # 只读:r,rb(非文字类型文件,上传,下载,图片) bytes----str
# f = open("今天天气真好",mode="rb")
# count = f.read()
# print(count,type(count))
# f.close() #只写:w
# 对于写文件没有此文件就会创建文件,
# f = open("今天天气好",mode="w",encoding="utf-8")
# f.write("今天天气好")
# f.close() # 先将原文件内容全部删除再写
# f = open("今天天气好",mode="w",encoding="utf-8")
# f.write("真的好呀")
# f.close() #wb 文件默认什么编码方式就以什么编码方式写进去
# f = open("今天天气好",mode="wb")
# f.write("zhendeshi ".encode("utf-8"))
# f.close() #追加 a 默认光标显示在最后一个字符,只能进行追加不能
# f = open("今天天气好",mode="a",encoding="utf-8")
# f.write("金额")
# f.close() #ab
# f = open("今天天气好",mode="ab")
# f.write("金额".encode("utf-8"))
# f.close() #a+
# f = open("今天天气好",mode="a+",encoding="utf-8")
# f.write("金额")
# f.seek(0)
# print(f.read())
# f.close() #读写 r+ 先把原文件读取出来,再写入
# f = open("今天天气真好",mode="r+",encoding="utf-8")
# print( f.read())
# f.write("yiyi,erer")
# f.close() #以bytes类型读写
# f = open("今天天气真好",mode="r+b")
# print( f.read())
# f.write("hahhahhahahhahahhahha".encode("utf-8"))
# f.close() #写读 w+ 先清除原文件,再写入
# f = open("今天天气真好",mode="w+",encoding="utf-8")
# f.write("aaaaaaaaaaaaaaaaaaaaa")
# print(f.read())
# f.close() #seek(调节光标)
# f = open("今天天气真好",mode="w+",encoding="utf-8")
# f.write("bbbbaaaaaaaaaaaaaaaaaa")
# f.seek(1)
# print(f.read())
# f.close() #功能详解
# f = open("今天天气真好",mode="r+",encoding="utf-8")
# # count = f.read(8) #读出来的都是字符
# f.seek(3) #按字节定位光标位置,一个英文一个字节表示,一个中文三个字节表示
# count = f.read()
# print(count)
# f.close() #断点续传 先定位光标位置,再调节光标位置
# tell (告诉你光标的位置)
# f = open("今天天气真好",mode="r+",encoding="utf-8")
# f.write("哈哈哈哈")
# count = f.tell()
# f.seek(count-9)
# print(f.read())
# f.close() #readline
# f = open("今天天气真好",mode="r+",encoding="utf-8")
# line = f.readline() #一行一行的读取
# print(line)
# f.close() #readlines 每一行当成列表中的一个元素,添加到line列表中
# f = open("今天天气真好",mode="r+",encoding="utf-8")
# line = f.readlines()
# print(line)
# f.close() #truncate 截取一段读取
# f = open("今天天气真好",mode="r+",encoding="utf-8")
# f .truncate(4)
# f.close() #同时打开多个文件
# with open("今天天气真好",mode="r+",encoding="utf-8") as f :open("今天天气好",mode="a",encoding="utf-8")as f1
# print(f.read(),f1.read() #登录注册
username = input("用户名:")
possword = input("密码:")
with open("登录",mode = "w",encoding="utf-8")as f:
f.write("{}\n{}".format(username,possword))
print("注册成功")
list =[]
count = 0
while count < 3:
uname = input("输入用户名:")
pwd = input("请输入密码")
with open("登录",mode = "r+",encoding="utf-8")as f1:
for line in f1:
list.append(line)
if uname == list[0].strip() and pwd ==list[1].strip():
print("登录成功")
break
else:
count += 1
print("输入错误")