r read 只读模式
w write 只写模式
a append 只追加模式
# r模式#当使用r模式时,如果文件不不存在将会直接报错withopen(r'a.txt', 'r', encoding = 'utf8') as f:
passpass没有任何功能,只是让代码不报错,与 ... 功能一致,通常使用pass
路径存在,正常打开文件并等待内容读取
withopen(r'a.txt', 'r', encoding = 'utf8') as f:
print(f.read()) #一次性读取文件中的所有内容
f.write('hello word') #报错# w模式#使用w模式,文件不存在,将会自动一个文件 文件存在则清空文件内容withopen(r'a.txt', 'w', encoding = 'utf8') as f:
f.write('hello 1\n') #将内容写入文件
f.write('hello 2\r') #将内容写入文件
f.write('hello 3\r') #将内容写入文件'''
\n \r 都是换行符号
最早时,\r\n表示换行
'''# a模式#路径不存在,自动创建文件,路径存在并不会清空文件withopen(r'a.txt', 'a', encoding = 'utf8') as f:
f.write('hello world') #将hello world 写入文件 print(f.read()) #报错,不能读
文件的操作模式
# t模式
文本模式 是默认模式
r rt
w wt
a at
1.只能操作文本文件
2.必须指定encoding参数
3.读写都是以字符串为最小单位
# b模式
二进制模式,可以操作任意类型文件
rb,wb,ab,,,b不能省略
1.可以操作任意类型文件
2.不需要指指定encoding参数
3.读写都是以bytes为最小单位
path1 = input(r'请输入文件路径>>>:')
path2 = input(r'请输入复制后文件路径>>>:')
withopen(rf'{path1}', 'r', encoding='utf8') as f:
res = f.read()
withopen(f'{path2}', 'w', encoding='utf8') as f1:
f1.write(res)
用户登录
点击展开
whileTrue:
# 打印菜单界面print('**********菜单**********\n1.登录\n2.注册')
# 获取用户选项
choice = input('请进行功能选择>>>:').strip()
if choice == '1':
username = input('请输入用户名>>>:').strip()
userpwd = input('请输入密码>>>:').strip()
withopen('userinfo.txt', 'r', encoding='utf8') as f:
for i in f:
if i.split('|')[0] == username and i.split('|')[1] == userpwd:
print('登录成功')
else:
print('用户名或密码错误')
if choice == '2':
whileTrue:
account = input('请输入你要注册的账号:>>>').strip()
pwd1 = input('请输入设置的密码>>>:').strip()
pwd2 = input('请再次输入设置的密码>>>:').strip()
if pwd1 == pwd2:
breakelse:
print('您两次输入的密码不一样')
withopen('userinfo.txt','r', encoding='utf8') as f1:
for info in f1:
if account in info:
print('用户名已存在')
else:
withopen('userinfo.txt', 'a', encoding='utf8') as f2:
f2.write(f'{account}|{pwd1}')
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人