Python3基础16——file对象测试数据的读写与操作

file txt xml html --->
mode 打开这个文件的模式,主要有以下:

'r'      open for reading (default)
'w'     open for writing, truncating the file first
'x'     create a new file and open it for writing
'a'     open for writing, appending to the end of the file if it exists
'b'    binary mode(二进制模式)
't'    text mode (default)
'+'     open a disk file for updating (reading and writing)
'U'     universal newline mode (deprecated)

r  w  a
r+   w+   a+
read  write  append
rb rb+ wb wb+ ab ab+ 做单元测试的时候

1:file文件open之后默认是r 只读模式 如果你要写入内容 报错:io.UnsupportedOperation: not writable
2:r+ 可读可写 先写的话 从头开始覆盖写 读光标之后的内容 读写跟着光标走
3:如果要写入中文 要注意编码格式encoding

1 file=open("python11.txt","r+",encoding='utf-8')
2 res=file.read()#进行完一次读取操作后 光标就到文末
3 file.write('卡卡777')
4 print(res)

4:w 只写 硬要去读 就会报错io.UnsupportedOperation: not readable
5:  w+ 可读可写 不管是w 还是w+ 如果文件存在 就直接清空 再重写,如果文件不存在 则新建一个文件 然后写

1 file=open("python12.txt","w",encoding='utf-8')
2 file.write("8889999")

6:a 追加 a+ 推荐

1 file=open("python12.txt","a",encoding='utf-8')
2 file.write("***Python106666")

如果文件存在 就直接追加写 写在后面 如果不存在 则新建一个文件进行结果写入

1 file=open("python13.txt","a",encoding='utf-8')
2 file.write("\n***Python106666")

重点掌握两种 r a

 1 file=open("python13.txt","r",encoding='utf-8')
 2 print(file.read()) #读取所有内容
 3 
 4 print(file.readline())#按行读取
 5 
 6 print(file.readlines())#读取多行 返回的是列表
 7 
 8 file_2=open("python12.txt","a",encoding='utf-8')
 9 print(file_2.write("20181011 file 操作")) # .write()打印出来的是一个int,表示写入的长度同时写入内容到文件
10 
11 file_2.writelines(["777\n","8888"])

 

转载于:https://www.cnblogs.com/monica711/p/9804865.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值