python read different type data

Ngchiwa Ng
1 min readMar 2, 2020

--

  • txt
with open('example.txt', 'r') as f:
data = f.readlines()
print(data)
  • json
import json
with open('example.json', 'r') as f:
data = json.load(f)
  • image with cv2
# pip install opencv-python
# export PYTHONPATH=/usr/local/lib/python3.7/site-packages/
import cv2
image = cv2.imread('.example.jpg')
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
plt.imshow(image)
plt.show()
  • image with Pillow
# pip install Pillow
from PIL import Image
image = Image.open('../ai100-4/day4/example.jpg')
plt.imshow(image)
plt.show()
  • image with skimage
pip install scikit-imageimport skimage.io as skio
image = skio.imread(".example.jpg")

plt.imshow(image)
plt.show()
  • npy file
import numpy as np
arr = np.load('./example.npy')
print(arr)
  • pkl file
import pickle
data = {}
with open('example.pkl', 'wb') as f:
pickle.dump(data, f)
with open(‘example.pkl’, ‘rb’) as f:
arr = pickle.load(f)

--

--

Ngchiwa Ng
Ngchiwa Ng

Written by Ngchiwa Ng

Backend/iOS Engineer, rock the world

No responses yet