Python-文件处理-t模式案例

#案例
#w模式用来创建全新的文件
#实现文件的copy
src_file_path=input("请输入要复制的文件路径:").strip()
dst_file_path=input("请输入要复制新的文件路径:").strip()
with open(r'{}'.format(src_file_path),mode="tr",encoding="utf-8") as tr,open(r'{}'.format(dst_file_path),mode="tw",encoding="utf-8") as tw:
# res=tr.read() #如果从硬盘读取的数据比较大,会撑爆内存的
# tw.write(res)
#使用for循环逐行读取每一行数据
for line in tr: #for循环每次读取文件一行
tw.write(line)
 


#案例
#实现注册
#如果用户输入存在则提示输入账号已存在,如果用户输入账号不存在,则追加到已有文件末尾

input_user = input("请输入账号:").strip()
input_password = input("请输入密码:").strip()
with open('userinfo2.txt',mode="rt",encoding="utf-8") as r_f,open("userinfo2.txt",mode="at",encoding="utf-8") as a_f:
for r1 in r_f: #使用for循环逐行读取文本文件中每一行(for循环逐行读取文本中每一行是以换行为分隔符进行读取)
if input_user in r1: #判断输入的账号是否在for循环循环取值中,如果在就提示账号已存在
print("输入的账号已存在")
break
else:
res_str="{0}:{1}\n".format(input_user,input_password)
a_f.write(res_str)



posted @ 2020-08-10 15:18  梁博客  阅读(152)  评论(0)    收藏  举报