mode and the x mode b

A, x mode and the mode b

1, x mode (to know)

x control file mode is the mode of operation is a write-only mode

Features: only write, unreadable; there is no written document is created, the error will exist.

Example:

with open('a.txt',mode='x',encoding='utf-8') as f:
    pass  #a不存在,创建a.txt空文件

with open('a.txt',mode='x',encoding='utf-8') as f:
    pass  #a存在,报错

with open('b.txt',mode='x',encoding='utf-8') as f:
    pass  #b不存在,创建b.txt空文件
    f.read()  #x是只写模式,不支持读操作,所以报错
    
with open('c.txt',mode='x',encoding='utf-8') as f:
    f.write('哈哈哈\n')  #c不存在,创建b.txt文件,写入'哈哈哈\n'

2, b mode

1, b and t contrastive pattern

t:

1) is the control mode read content file

2) are read as a string (Unicode) units

3) only for text files

4) must be specified character coding, i.e. encoding parameters must be specified

b:

1) is the control mode read content file

2) are read in bytes

3) may file for all

4) must not be specified character coding, i.e. must not specify the encoding parameter

Comparison Summary:

1) in operation mode plain text files t help us save a link encoding and decoding, b mode you need to manually encode and decode, so in this case t is more convenient mode, plain text mode is recommended t
2) for non text files (such as images, video, audio, etc.) can only use the b mode, compatibility mode b

2, the basic model must be used together with b r, w, b in combination with

1、rb

with open(r'美图.jpg',mode='rb',encoding='utf-8') as f:
    res=f.read() # utf-8的二进制->unicode
    print(res)

2、wb

with open(r'e.txt',mode='wb') as f:
    f.write('雷猴啊!hello'.encode('utf-8'))

3, from

with open(r'e.txt',mode='ab') as f:
    f.write('雷猴啊!hello'.encode('utf-8'))

2, b mode practical case

# rb和wb写成的文件拷贝工具
src_file=input('源文件路径>>: ').strip()
dst_file=input('源文件路径>>: ').strip()
with open(r'{}'.format(src_file),mode='rb') as f1,\
    open(r'{}'.format(dst_file),mode='wb') as f2:
    # res=f1.read() # 内存占用过大
    # f2.write(res)

    for line in f1:
        f2.write(line) #一次只读写一行

3, b mode cycle value

Controlling the amount of data read each time their data: a way

with open(r'美图.jpg',mode='rb') as f:
    while True:
        res=f.read(1024) # 自定义每次循环读取的字节数为1024
        if len(res) == 0:
            break  #文件读完最后一行后,len长度为0,退出循环
        print(len(res))

Second way:

(Read directly in units, when his party content will lead to a one-time data read into the content too long too large)

with open(r'美图.jpg',mode='rb') as f:
    for line in f:  #用for循环每次只读一行
        print(line)  

Guess you like

Origin www.cnblogs.com/zhangtieshan/p/12508072.html