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.写入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()

3.读入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)

4.读入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)

猜你喜欢

转载自www.cnblogs.com/caiyishuai/p/9462833.html