python将多个txt文档转为一个excel中的多个sheet

安装工具:

          apt install -y python-pip

          pip install openpyxl

方法一:

# cat test.py
import os,sys,openpyxl
from openpyxl import Workbook

#os.chdir('C:/Users/IsBean/Desktop')
wb = Workbook()
outputfile=sys.argv[-1]


def write_excel(txt_name, sheet):
    f1 = open(txt_name, 'r')
    lines = f1.readlines()
    for line in lines:
        split_line = line.split('\t')
        sheet.append(split_line)
for inputfile in sys.argv[1:-1]:
    sheetName=inputfile
    sheet = wb.create_sheet(sheetName)
    write_excel(inputfile, sheet)
    wb.save(outputfile)
wb1 = openpyxl.load_workbook(outputfile)
del wb1['Sheet']   #删掉多余的Sheet空表页表
wb1.save(outputfile)
 

执行: python test.py xian1.txt xian2.txt xian3.txt xian.xlsx

python2版本的,python3不适用

方法二:自己自定文件名,遍历

root@tian-1:/tmp# cat test.py 
# -*- encoding: utf-8 -*-
import os,sys,openpyxl
from openpyxl import Workbook

wb = Workbook()
dirname=raw_input('请输入存放txt的目录名:')
outputfile=raw_input('请输入要写入的excel名:')
alltxt=os.listdir(dirname)

def write_excel(txt_name, sheet):
    f1 = open(txt_name, 'r')
    lines = f1.readlines()
    for line in lines:
        split_line = line.split('\t')
        sheet.append(split_line)
for inputfile in alltxt:
    sheetName=inputfile
    sheet = wb.create_sheet(sheetName)
    write_excel(inputfile, sheet)
    wb.save(outputfile)
wb1 = openpyxl.load_workbook(outputfile)
del wb1['Sheet']
wb1.save(outputfile)
 

执行:/tmp/a下存放了所有要转换的txt文档

~#cd /tmp

/tmp# python test.py 
请输入存放txt的目录名:a
请输入要写入的excel名:xian.xlsx
 

引用原文:

https://blog.csdn.net/weixin_38987362/article/details/81303865

https://juejin.im/entry/5b3b2c7d6fb9a04fe820c5a3

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值