标签:open log pytho user rip 内容 模式 打开 操作模式
# 以t模式为基准操作
# 1.r:只读模式:文件不存在时报错,文件存在时指针跳到开始位置
# input_username = input("username:")
# input_password = input("password:")
#
# with open(‘a.txt‘, mode=‘rt‘, encoding=‘utf-8‘) as f:
# for line in f: # 读取f的每一行
# username, password = line.strip().split(‘:‘)
#
# if input_username == username and input_password == password:
# print(‘login successful‘)
# break
# else:
# print(‘wrong username or password‘)
# 2.w:只写模式:文件不存在时会创建空文件,文件存在时会清空文件,指针跳到开始位置
# with open(‘c.txt‘, mode=‘wt‘, encoding=‘utf-8‘) as f:
# f.write(‘哈哈哈\n‘)
# 强调1:在以w模式打开文件没有关闭的情况下,连续写入,新内容总是跟在旧内容之后
# with open(‘c.txt‘, mode=‘wt‘, encoding=‘utf-8‘) as f:
# f.write(‘哈哈哈1‘)
# f.write(‘哈哈哈2\n‘)
# f.write(‘哈哈哈3\n‘)
# 3.a:只追加写模式:文件不存在时创建空文档,文件存在时,指针会直接跳到文件末尾
# with open(‘c.txt‘, mode=‘at‘, encoding=‘utf-8‘) as f:
# f.write(‘哈哈哈4\n‘)
# 注册功能
# name = input("user name:")
# password = input("password:")
#
# with open("info.txt", mode="at", encoding="utf-8") as f:
# f.write(‘{}:{}\n‘.format(name, password))
# 文件copy工具
# src_file = input("path1:").strip()
# dst_file = input("path2:").strip()
# with open(r‘{}‘.format(src_file), mode=‘rt‘, encoding=‘utf-8‘) as f1, \
# open(r‘{}‘.format(dst_file), mode=‘wt‘, encoding=‘utf-8‘) as f2:
# res = f1.read()
# f2.write(res)
# 4.+:不能单独使用,必须配合r,w,a # 了解
with open(‘a.txt‘, mode=‘rt+‘, encoding=‘utf-8‘) as f:
f.write(‘aaa‘) # 覆盖原来内容
with open(‘a.txt‘, mode=‘wt+‘, encoding=‘utf-8‘) as f:
f.write(‘aaa‘)
with open(‘a.txt‘, mode=‘at+‘, encoding=‘utf-8‘) as f:
f.write(‘aaa‘)
标签:open log pytho user rip 内容 模式 打开 操作模式
原文地址:https://www.cnblogs.com/wyless/p/14930415.html