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

file=open("python11.txt","r+",encoding='utf-8')
res=file.read()#进行完一次读取操作后 光标就到文末
file.write('卡卡777')
print(res)
4:w 只写 硬要去读 就会报错io.UnsupportedOperation: not readable
5:w+ 可读可写 不管是w 还是w+ 如果文件存在  就直接清空 再重写,如果文件不存在 则新建一个文件  然后写
file=open("python12.txt","w",encoding='utf-8')
file.write("8889999")
6:a 追加 a+  推荐

file=open("python12.txt","a",encoding='utf-8')
file.write("***Python106666")
如果文件存在 就直接追加写 写在后面  如果不存在 则新建一个文件进行结果写入
file=open("python13.txt","a",encoding='utf-8')
file.write("\n***Python106666")
#重点掌握两种  r  a
file=open("python13.txt","r",encoding='utf-8')
print(file.read()) 读取所有内容

print(file.readline())按行读取

print(file.readlines())#读取多行 返回的是列表

file_2=open("python12.txt","a",encoding='utf-8')
print(file_2.write("20181011 file 操作"))  #打印出来的是一个int,写入的长度

file_2.writelines(["777\n","8888"])

你可能感兴趣的:(Python3)