python中excel与txt文件相互转换

 此处的txt_file 和excel_file都是文件的地址。下面函数用于将已知地址的txt文件转换为相同目录下的excel文件,并按照空格对每一行进行划分。

import pandas as pd
import re
from openpyxl import load_workbook
def txt_to_excel(txt_file):
    # 读取txt文件内容
    with open(txt_file, 'r') as file:
        data = file.readlines()

    # 按照\n分隔每一行,按空格分隔每一格子,处理多个空格的情况
    data = [re.split(r'\s+', line.strip()) for line in data]

    # 将数据转换为DataFrame 
    df = pd.DataFrame(data)

    # 将DataFrame写入excel文件
    excel_file = txt_file.replace('.txt', '.xlsx') #创建统一目录下的excel文件
    df.to_excel(excel_file, index=False, header=False)

    print(f'{txt_file} 已成功转换为 {excel_file}')
    return excel_file #返回一个excel文件,可以对该文件进行再加工

在将excel转化为新的文本文件,命名为renew,保存在统一目录下,没有return,因为不需要对其进行再处理。

import xlrd
def excel_to_txt(excel_file):
    workbook = xlrd.open_workbook(excel_file) #选择一个excel文件
    worksheet = workbook.sheet_by_index(0)  #选择一种的一张表,0表示选择了第一张表
    txt_file = os.path.join(os.path.dirname(excel_file), 'renew.txt') #新建一个文本文件在共一目录下
    with open(txt_file ,'w') as file:
        for row_index in range(worksheet.nrows):  #nrows表示总行数
            for col_index in range(worksheet.ncols):  #表示总列数
                file.write( str(worksheet.cell_value(row_index,col_index)) +'\t\t') 
                #以'\t\t'为间隔
            file.write('\n')

  • 16
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值