python对文件的读写(持续更新中)
1、读写txt文件
读取文件夹中所有的txt文件,并且拼接成字符串
代码:
all_text=""
txt_data=[]
for s in range(10,100):
try:
s=str(s)
txt_name="path/%s.txt" % s
f=open(txt_name,"r")
all_text=all_text+f.read()
f.close
except:
continue
2、读写excel文件
3、读写图片
4、读写多维数组
多维数组
a.tofile()
np.fromfile()
np.save()
np.savez()
np.load()
详细代码和注释
# -*- coding: utf-8 -*-
import numpy as np
# 存贮和读取1维或2维数组
def foo1():
a = np.arange(100).reshape((20, 5))
# 写入文件
np.savetxt(fname="data.csv", X=a, fmt="%d",delimiter=",")
# 读取文件
b = np.loadtxt(fname="data.csv", dtype=np.int, delimiter=",")
print(b)
# 写入读取多维数组,数组结构会丢失
def foo2():
# 可以将数据结构存入一个文件,读取
a = np.arange(100).reshape((10, 5, 2))
# 写入文件
a.tofile(file="data.dat", sep=",", format="%s")
# 读取文件
b = (np.fromfile(file="data.dat", dtype=np.int, count=-1, sep=",")
.reshape((10, 5, 2)))
print(b)
# 便捷的存取读出npy文件
def foo3():
a = np.arange(100).reshape((10, 5, 2))
# 存储
np.save(file="data.npy", arr=a)
# 读取
b= np.load(file="data.npy")
print(b)