码迷,mamicode.com
首页 > 编程语言 > 详细

22.Python:文件操作模式详解

时间:2021-06-25 17:15:33      阅读:0      评论:0      收藏:0      [点我收藏+]

标签: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‘)

22.Python:文件操作模式详解

标签:open   log   pytho   user   rip   内容   模式   打开   操作模式   

原文地址:https://www.cnblogs.com/wyless/p/14930415.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!