Python各种文件IO操作
有段时间不打代码就会忘记各种文件的读取和存储,不如自己整理一个,忘了就来看下
图片
图片的读取
使用PIL
库
from PIL import Image
img = Image.open(img_path)
可以非常方便得对img
进行图像的各种变换
如果需要存成numpy
数组,使用
import numpy as np
np_img = np.array(img)
使用matplotlib
库
import matplotlib.pyplot as plt
img = plt.imread(img_path)
得到的是numpy
数组,也很方便
图片的保存
如果是PIL
库的Image
类,直接调用save()
方法
from PIL import Image
img = Image.open(img_path)
img.save(save_path)
如果使用matplotlib
库读取
plt.savefig(save_path)
也可以参照下面保存为numpy
数组
numpy
numpy
数组的读取与存储使用
np.save(save_path, save_np)
np.load(load_path)
txt文件
打开
使用open
打开
f = open(txt_path)
# processing file
f.close()
使用with
则不需要调用close()
方法
with open(txt_path) as f:
# processing file
如果遇到报错
UnicodeDecodeError: 'gbk' codec can't decode byte 0x80 in position 439: illegal multibyte sequence
读取的时候加上编码设置
with open(txt_path, encoding='UTF-8') as f:
# processing file
逐行读取
line = f.readline()
while line:
print(line)
或者
lines = f.readlines()
for line in lines:
print(line)
去除line
中不想要的元素(例如,英文字母)
filter(lambda c: '' if c.isalpha() else c, line)