简介
python读写三类文件
excel文件
txt文件
mat文件文章来源地址https://www.toymoban.com/news/detail-638932.html
代码
"""
@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)
代码讲解链接
在这里插入代码片
文章来源:https://www.toymoban.com/news/detail-638932.html
到了这里,关于[代码案例]学会python读写各类文件的操作(excel,txt,mat)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!