总结
# 以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')
以上是内存溢出为你收集整理的22.Python:文件 *** 作模式详解全部内容,希望文章能够帮你解决22.Python:文件 *** 作模式详解所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)