python 二進制

1.二進制

在電腦的數(shù)據(jù)存儲中任何東西都可以用二進制來表示,這里我們介紹一種用二進制讀寫的方式。

  import os
import pickle
srcfloder = "./exm.py"
with open(srcfloder,'rb') as fin:
  a = fin.read()
  print(a)
  with open("./exm.bin",'wb') as f:
    pickle.dump(a,f,-1)

with open("exm.bin",'rb') as f:
  print(a)
  b = pickle.load(f)
  print(b)

b'import os\r\nimport pickle\r\nsrcfloder = "./exm.py"\r\nwith open(srcfloder,\'rb\') as fin:\r\n  a = fin.read()\r\n  print(a)\r\n  with open("./exm.bin",\'wb\') as f:\r\n    pickle.dump(a,f,-1)\r\n\r\nwith open("exm.bin",\'rb\') as f:\r\n  print(a)\r\n  b = pickle.load(f)\r\n  print(b)'
b'import os\r\nimport pickle\r\nsrcfloder = "./exm.py"\r\nwith open(srcfloder,\'rb\') as fin:\r\n  a = fin.read()\r\n  print(a)\r\n  with open("./exm.bin",\'wb\') as f:\r\n    pickle.dump(a,f,-1)\r\n\r\nwith open("exm.bin",\'rb\') as f:\r\n  print(a)\r\n  b = pickle.load(f)\r\n  print(b)'
b'import os\r\nimport pickle\r\nsrcfloder = "./exm.py"\r\nwith open(srcfloder,\'rb\') as fin:\r\n  a = fin.read()\r\n  print(a)\r\n  with open("./exm.bin",\'wb\') as f:\r\n    pickle.dump(a,f,-1)\r\n\r\nwith open("exm.bin",\'rb\') as f:\r\n  print(a)\r\n  b = pickle.load(f)\r\n  print(b)'

這里我們可以看到讀入和寫出是一樣的,在這里我們需要注意,我們以什么方式來讀取文件,就會以什么方式來寫出文件。

import os
import pickle
import mxnet as mx
import cv2 as cv
import numpy as np
from  mxnet import nd
from PIL import Image
with open("./1.jpg",'rb') as fin:
  a = fin.read()
  img = mx.image.imdecode(a,to_rgb=0)
  img = nd.transpose(img, axes=(2, 0, 1))
  xiaowang = float(img.asnumpy())
  cv.imwrite("2.jpg", xiaowang)
  print(a)
  with open("./tupian.bin", 'wb') as f:
    pickle.dump(a, f, protocol=pickle.HIGHEST_PROTOCOL)

with open("tupian.bin",'rb') as f:
  print(a)
  b = pickle.load(f)
  img = mx.image.imdecode(b)
  img = nd.transpose(img, axes=(2, 0, 1))

  print(b)
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容