Python文件字节读写

import os


filename = 'test.txt'

#把文件内容以byte字节形式读写到缓冲区中。
def read_into_buffer(filename):
    buf = bytearray(os.path.getsize(filename))
    with open(filename, 'rb') as f:
        f.readinto(buf)
    f.close()
    return buf


if not os.path.exists(filename):
    print("创建"+filename)
    with open(filename, 'w', encoding='UTF-8') as f:
        f.write('zhang\nphil\n2019')
        f.close()
    print("文件尺寸"+str(os.path.getsize(filename)))


with open(filename, 'r', encoding='UTF-8') as f:
    data = f.read()
    print(data)
f.close()


if os.path.exists(filename):
    print("存在"+filename)
    with open(filename, 'r', encoding='ascii') as f:
        for line in f:
            print(line, end='')
    f.close()


#以字节数据方式写文件。
with open(filename, 'ba') as f:
    buf = bytearray(b"csdn")
    f.write(buf)
f.close()


print(list(read_into_buffer(filename)))

 

运行后输出:

创建test.txt
文件尺寸17
zhang
phil
2019
存在test.txt
zhang
phil
2019[122, 104, 97, 110, 103, 13, 10, 112, 104, 105, 108, 13, 10, 50, 48, 49, 57, 99, 115, 100, 110]

 

你可能感兴趣的:(Python,Python)