LBOcean

python如何将txt文本导入excel实例

如何将txt文本导入excel实例

这里我们用python中的random.randint方法在txt文本当中随机生成100份成绩

这里我的项目文件名为to_score.py

import random

#随机写入100个学生的数学,计算机分数到txt文本当中
with open("score.txt","w") as fw:
    num_s = 1
    num_e = 100
    for i in range(num_s,num_e+1):
    #遍历1-100随机生成100份成绩
        math = random.randint(10,100)
        computer = random.randint(10,100)
        #\n是换行符,若有不会使用format方法的请自行查询!
        fw.write("{},{},{}\n".format(i,math,computer))
    #若with open as 放在这个位置,则read出来的是null值
    #因为read()读取时是从指针位置开始读取的.所以这里一边写入数据一边读取数据,读取出来的只有空值.
with open(r"score.txt","r") as fr :
    print(fr.read())#read()读取文档全部内容,查看是否写入

以上操作完成之后,你会发现你的项目当中会多出一个score.txt.
这就是随机生成的100份成绩

在这里插入图片描述

接下来我们新创建一个sheet.py(名字随意)

导入openpyxl包.
利用相关的方法把txt文本导入excel表格

from openpyxl import Workbook
#导入openpyxl包
wb = Workbook()#创建一个excel
sheet = wb.active#获取当前excel的sheet
datas = None#定义一个空值,接收score.txt的参数

with open("score.txt","r") as fr :#读取上面txt的数据,这里我的txt文本命名为score.txt
    datas = fr.readlines()

sheet["A1"] = "学号" #excel中:A列第一行,写入"学号"
sheet["B1"] = "数学"
sheet["C1"] = "计算机"

for i in range(len(datas)):#遍历datas的长度,100行
    id_,math_,computer_ = datas[i].split(",")
    """
    当i等于1时这里的 id_,math,computer=(to_execl.py里的)i,math,computer
    以此类推
    """
    row = str(i + 2)
    sheet["A" + row] = id_
    sheet["B" + row] = math_
    sheet["C" + row] = computer_

wb.save("score.xlsx") #保存excel名字随意,后缀要注意

这样我们完成了对txt导入excel的相关操作.

在这里插入图片描述

posted on 2020-12-16 14:34  LBOcean  阅读(4679)  评论(0编辑  收藏  举报

导航