python如何将txt格式的文件转为Excel格式

1、代码如下:

# -*- coding:utf-8 -*-
import os
import xlwt
import xlrd
import xlutils
from xlutils.copy import copy
import re


def saveBrankExcel():
    with open("output1/shangcheCarBrank.txt","r",encoding="utf-8") as fp:
        datas = fp.readlines()
        count = 1
        for i in datas:
            dict1 = {}
            # 用正则取出需要的保存数据内容
            dict1["makename"] = re.findall("'makename': '(.*?)'", i)[0]
            dict1["makeid"] = re.findall("'makeid': '(.*?)'", i)[0]
            dict1["modelname"] = re.findall("'modelname': '(.*?)'", i)[0]
            dict1["modelid"] = re.findall("'modelid': '(.*?)'", i)[0]
            dict1["trimname"] = re.findall("'trimname': '(.*?)'", i)[0]
            dict1["trimid"] = re.findall("'trimid': '(.*?)'", i)[0]
            dict1["price"] = re.findall("'price': '(.*?)'", i)[0]
            print(dict1)
            saveData(dict1,count)
            count = count+1
def saveData(getdata,count):
    # 建立文件夹存放Excel文件
    folder_name = "output1"
    if not os.path.exists(folder_name):
        os.mkdir(folder_name)
    file_name = "shangcheBrank" + ".xls"
    file_path = folder_name + "/" + file_name
    if not os.path.exists(file_path):
        # 保存xls格式
        # 创建一个workbook并设置编码格式
        workbook = xlwt.Workbook(encoding="utf-8")
        sheet = workbook.add_sheet(u"工作表1")
        # 创建行标题内容
        header = [u"makename", u"makeid", u"modelname", u"modelid", u"trimname", u"trimid", u"price"]
        for index, item in enumerate(header):
            # 参数对应为(行,列,值)
            sheet.write(0, index, item)
        # 保存
        workbook.save(file_path)

    # 读取一个Excel文件
    oldw = xlrd.open_workbook(file_path, formatting_info=True)
    # 复制表
    neww = copy(oldw)
    # neww = xlutils.copy.copy(oldw)
    # 定位新的表 使用get_sheet方法
    newsheet = neww.get_sheet(0)
    print(type(getdata))
    lines = [getdata['makename'], getdata['makeid'], getdata['modelname'], getdata['modelid'], getdata['trimname'], getdata['trimid'],getdata['price']]
    for i, ite in enumerate(lines):
        newsheet.write(count, i, ite)
    # 保存
    neww.save(file_path)


saveBrankExcel()

2、结果如下:
这里写图片描述

  • 0
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值