python中读写二进制文件

参考:

  1.  
     
  2.  
    # f = open("test4.txt", 'w')
  3.  
    #
  4.  
    # f.write(b'hello world') # TypeError: write() argument must be str, not bytes
  5.  
    #
  6.  
    # f.close()
  7.  
     
  8.  
    f = open( "test4.txt", 'wb') # 二进制写模式
  9.  
     
  10.  
    f.write( b'hello world') # 二进制写
  11.  
     
  12.  
    f.close() # 关闭文件
  13.  
     
  14.  
    f = open( "test4.txt", 'rb') # 二进制读
  15.  
     
  16.  
    print(f.read()) # b'hello world' 打印读出来的数据
  17.  
     
  18.  
    f.close() # 关闭文件
  19.  
     

猜你喜欢

转载自www.cnblogs.com/kuangke/p/12390615.html