22.Python:文件操作模式详解
2021/6/25 12:56:50
本文主要是介绍22.Python:文件操作模式详解,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
# 以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:文件操作模式详解的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-12-20Python编程入门指南
- 2024-12-20Python编程基础与进阶
- 2024-12-19Python基础编程教程
- 2024-12-19python 文件的后缀名是什么 怎么运行一个python文件?-icode9专业技术文章分享
- 2024-12-19使用python 把docx转为pdf文件有哪些方法?-icode9专业技术文章分享
- 2024-12-19python怎么更换换pip的源镜像?-icode9专业技术文章分享
- 2024-12-19Python资料:新手入门的全面指南
- 2024-12-19Python股票自动化交易实战入门教程
- 2024-12-19Python股票自动化交易入门教程
- 2024-12-18Python量化入门教程:轻松掌握量化交易基础知识