Python将数据写入excel或者txt,读入csv格式或xls文件,写入csv(写一行空一行解决办法)

1.写入excel,一开始不需要自己新建一个excel,会自动生成

attribute_proba是我写入的对象

Python将数据写入excel或者txt,读入csv格式或xls文件,写入csv(写一行空一行解决办法)

 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="",否则会写一行空一行

Python将数据写入excel或者txt,读入csv格式或xls文件,写入csv(写一行空一行解决办法)

    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文件

Python将数据写入excel或者txt,读入csv格式或xls文件,写入csv(写一行空一行解决办法)

    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

Python将数据写入excel或者txt,读入csv格式或xls文件,写入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)

Python将数据写入excel或者txt,读入csv格式或xls文件,写入csv(写一行空一行解决办法)

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

Python将数据写入excel或者txt,读入csv格式或xls文件,写入csv(写一行空一行解决办法)

    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)
上一篇:java测试之文件操作


下一篇:hibernate坑边闲话2