Python文件字节读写
  TEZNKK3IfmPf 2023年11月14日 21 0
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]
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月14日 0

暂无评论

推荐阅读
  TEZNKK3IfmPf   2024年05月31日   32   0   0 python开发语言
  TEZNKK3IfmPf   2024年05月31日   25   0   0 python
  TEZNKK3IfmPf   2024年05月31日   25   0   0 python
TEZNKK3IfmPf