python读写三类文件
excel文件
txt文件
mat文件
"""
@Description: python 读写各类文件 操作
"""
import scipy as scipy
from scipy.io import loadmat
import xlwt
import xlrd
'''
读写excel文件
'''
workbook = xlrd.open_workbook('test1.xlsx')
worksheet = workbook.sheet_by_name('Sheet1')
c_value = worksheet.cell_value(0, 0) # 获取单元格数据
print(c_value)
r_values = worksheet.row_values(0) # 获取行数据
print(r_values)
c_values = worksheet.col_values(0) # 获取行数据
print(c_values)
# 获取全部数据存入变量X
X = []
for r in range(worksheet.nrows):
X.append(worksheet.row_values(r))
print('\n', X)
# 写入excel表
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet("sheet_0")
for i in range(len(X)):
for j in range(len(X[i])):
worksheet.write(i, j, float(X[i][j]))
workbook.save("DATA1.xls")
'''
读写.txt文件
'''
f = open('2.txt', encoding='utf-8')
data = f.readlines() # 读取所有行
print(data)
f = open('2.txt', encoding='utf-8')
data = []
for line in f:
data.append(line.strip())
print(data)
# 写
with open("DATA2.txt", "w", encoding='utf-8') as f:
f.write("这里写点什么东西好呢")
'''
读写.mat文件
'''
scipy.io.savemat("hahaha.mat", {'data': data, 'X': X})
matdata = loadmat('hahaha.mat')
data = matdata['data']
X = matdata['X']
print('\n')
print(data)
print(X)
在这里插入代码片