Python将数据写入excel或者txt,读入csv格式或xls文件
Posted 蔡军帅
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python将数据写入excel或者txt,读入csv格式或xls文件相关的知识,希望对你有一定的参考价值。
1.写入excel,一开始不需要自己新建一个excel,会自动生成
attribute_proba是我写入的对象
import xlwt myexcel = xlwt.Workbook() sheet = myexcel.add_sheet(\'sheet\') si=-1 sj=-1 for i in attribute_proba: si=si+1 for j in i: sj=sj+1 sheet.write(si,sj,str(j)) sj=-1 myexcel.save("attribute_proba_big.xls")
2.写入csv,注意要打上 newline="",否则会写一行空一行
import csv with open("tech_problem.csv","w",newline="") as csvfile: writer = csv.writer(csvfile) for i in range(52): writer.writerow([i,bol[i]])
slast的结构是有列表组成的列表
ls=[]
ls.append(number)
slast.append(ls)
可以直接写
import csv with open("final.csv","w",newline="") as csvfile: writer = csv.writer(csvfile) writer.writerow([\'A\',\'B\',\'C\',\'D\',\'E\',\'F\',\'G\',\'H\',\'I\',\'J\',\'K\',\'L\',\'M\',\'N\',\'O\',\'P\',\'Q\',\'R\',\'S\',\'T\']) writer.writerows(slast)
3.写入txt,一开始就需要你新建一个txt文件
f=open(\'F:/goverment/myfinalcode/predict.txt\', \'w\') for i in range(s): f.write(str(predict[i])) f.write(\'\\n\') f.write("写好了") f.close()
4.读入csv
file = \'F:/goverment/myfinalcode/test_big.csv\' fo=open(file) ls=[] for line in fo: line=line.replace("\\t",",") line=line.replace("\\n",",") line=line.replace("\\"",",") ls.append(line.split(",")) for i in ls: li=[] for j in i: if j == \'\': continue li.append(str(j)) testdata.append(li)
from pandas import read_csv data_set = read_csv("F:/goverment/excel operating/type_in.csv") data = data_set.values[:, :] test_data = [] for line in data: ls = [] for j in line: ls.append(j) test_data.append(ls)
5.读入xls
import xlrd file = \'F:/goverment/myfinalcode/test_big_label.xls\' wb = xlrd.open_workbook(file) ws = wb.sheet_by_name("Sheet1") for r in range(ws.nrows): col = [] for c in range(ws.ncols): col.append(ws.cell(r, c).value) testlabel.append(col)
6.读入txt
with open("test.txt", "r") as f: data = f.readlines() print(data)
以上是关于Python将数据写入excel或者txt,读入csv格式或xls文件的主要内容,如果未能解决你的问题,请参考以下文章
用python从符合一定格式的txt文档中逐行读取数据并按一定规则写入excel(openpyxl支持Excel 2007 .xlsx格式)