文件与IO --读写字节数据中的一些问题

问题:

读写二进制文件,比如图片、文件、视频等

函数:

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

读取写入模式:

使用模式为 rb 或 wb 的 open() 函数来读取或写入二进制数据。

#rb:使用decode进行解码读取:'rb'/str.decode()
with open('somefile.bin','rb')as f: data=f.read() print(data) #b'testcontent' type:<class 'bytes'> print(data.decode('utf-8'))#testcontent 读取文件指定utf-8解码data数据


#wb:b'str'字节文件直接写入 这里涉及str to byte

with open('somefile.bin','ab') as f:
      data=b'hello_word'
     f.write(data)
# testcontenthello_world

#wb:使用encode进行编码写入 'wb'/ str.encode()
with open('somefile.bin','ab') as f:
      data= ' '+'starting'
      f.write(data.encode('utf-8'))
'''

  testcontenthello_world
  starting

'''



注意:
with open('somefile.bin','rb',encoding='utf-8')as f:
编码报错 binary mode doesn't take an encoding argument#rb操作时不支持指定encoding参数;
同样wb也没有

  

special

二进制I/O还有一个鲜为人知的特性就是数组和C结构体类型能直接被写入,而不需要中间转换为自己对象

 #array模块  https://www.cnblogs.com/yescarf/p/13787181.html

#通过array直接写入二进制数组

In [55]: import array

In [56]: nums=array.array('i',[0,0,0,1,0])

In [57]: with open('data.bin','wb') as f:
...: f.write(nums)

In [58]: with open('data.bin','rb') as f:
...: print(f.read())
...:

 很多对象还允许通过使用文件对象的 readinto() 方法直接读取二进制数据到其底层的内存中去。比如:

>>> import array
>>> a = array.array('i', [0, 0, 0, 0, 0, 0, 0, 0])
>>> with open('data.bin', 'rb') as f:
...     f.readinto(a)
...
16
>>> a
array('i', [1, 2, 3, 4, 0, 0, 0, 0])
>>>
原文地址:https://www.cnblogs.com/yescarf/p/13787342.html