python-txt文件处理

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+:可读可写,根据光标所在位置开始执行。先写的话,光标在第一个位置—覆盖写,后读的时候根据光标所在位置往后读;但不管读几个字符,读过后,光标在文末

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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值