1、打开文件的模式主要有,r、w、a、r+、w+、a+

file = open('test.txt',mode='w',encoding='utf-8')
file.write('hello,world!')
file.close() #由此txt文件内容为hello,world!

2、r+:可读可写,根据光标所在位置开始执行。先写的话,光标在第一个位置---覆盖写,后读的时候根据光标所在位置往后读;但不管读几个字符,读过后,光标在文末

  建议:操作时,读和写分开比较好,编码时涉及到中文用utf-8

file = open('test.txt',mode='r+',encoding='utf-8')
file.write('Monday!')
content = file.read() #content = file.read(6),表示读取6个字符,但只要读过后,光标会在文末
file.close() #由此txt文件内容为:Monday!hello,world!
print(content) #打印结果为:hello,world!
file = open('test.txt',mode='r+',encoding='utf-8')
content = file.read()
file.write('Monday!')
file.close() #由此txt文件内容为:hello,world!Monday!
print(content) #打印结果为:hello,world!

3、w+:可读可写。不管w还是w+,存在文件会清空重写,不存在文件会新建文件写;

  因为会清空重写,所以不建议使用

file = open('test.txt',mode='w+',encoding='utf-8')
file.write('哮天犬!')
file.close() #由此txt文件内容为:哮天犬!

4、a:追加写。如果文件存在追加写,如果文件不存在,则新建文件写

file = open('test.txt',mode='a',encoding='utf-8')
file.write('哮天犬!')
file.close() #由此txt文件内容为:哮天犬!哮天犬!

5、读写多行操作

写多行

file = open('test.txt',mode='a',encoding='utf-8')
file.writelines(['\n二哈!','\n土狗!']) #此处的\n为换行
file.close()
文件内容:
哮天犬!
二哈!
土狗!

读多行

file = open('test.txt',mode='r',encoding='utf-8')
content = file.readlines() #读出的为列表
file.close()
print(content)
控制台输出:['哮天犬!\n', '二哈!\n', '土狗!']

总结:a:建议使用时读写操作分离,即不建议使用w+、r+、a+

   b:写的话,不建议使用w,建议使用a;读的话,使用r

      c:使用中文时,编码要使用utf-8

最新文章

  1. <<< 判断提交方式是get还是post
  2. JSBinding+Bridge.Net:框架代码与逻辑代码的关系
  3. 第七节:Class与Style绑定
  4. spark Basic code demo
  5. [转]highcharts图表入门之:如何让highcharts图表自适应浏览器窗体的大小或者页面大小
  6. 蓝牙的L2CAP协议
  7. python的相对路径导入问题
  8. [Unix.C]文件I/O
  9. C++ 多态性浅谈
  10. SQL Server Mysql primary key可更新性分析
  11. vsftpd配置seccomp_sandbox=NO
  12. 3537. 【NOIP2013提高组day2】华容道(搜索 + 剪枝)
  13. git目录
  14. Hdoj 2046.骨牌铺方格 题解
  15. FLEX外包团队:Flex例子DEMO源码
  16. 6.HTML+CSS制作一双眼睛
  17. 【转】Closeable, Readable, Flushable, Appendable
  18. Winform选择目录路径与选择文件路径
  19. 纯js无缝滚动
  20. Spring MVC 处理列表和数组数据

热门文章

  1. 初识Prometheus
  2. java SHA1加密算法
  3. 微信内置浏览器video标签自动全屏的问题
  4. httpclient访问接口步骤
  5. 输入、输出(iostream)
  6. 五 Hibernate的其他API,Query&Criteria&SQLQuery
  7. Matplotlib 入门
  8. docker安装mysql中注意事项
  9. Element 以二进制的形式 自定义上传图片
  10. RAM和ROM的区别