读取excel dataframe split 写入excel

import pandas as pd
import os
import copy
import shutil
import re
import xlrd, xlwt
from xlutils.copy import copy as xl_copy
from openpyxl import load_workbook
import numpy as np


def getInfoOfDigtalChannel(path):
    # 去除首字母D, =.=
    getInfo = pd.read_excel(path, sheet_name=Digital, dtype=str, keep_default_na=False, header=1)
    info = pd.DataFrame(getInfo.iloc[:, :])
    if info.empty:
        print('file is empty')
    else:
        for i in range(0, info.keys().size):
            if re.search('DUT.*Channel', info.keys()[i]):
                for j in range(0, len(info)):
                    # print(re.split('^D',str(info.iat[j, i]))[-1])
                    info.iat[j, i] = re.split('^D', str(info.iat[j, i]))[-1]
                    # print(info.iat[j, i])
    fileTo = os.path.join(OutputPath, 'channel_map_'+Digital+'.xlsx')

    info.to_excel(fileTo, header=1, index=False, encoding='utf-8', sheet_name=Digital)


def getInfoOfDPSChannel(path):
    # 去除首字母D, =.=
    getInfo = pd.read_excel(path, sheet_name=Power, dtype=str, keep_default_na=False, header=1)
    info = pd.DataFrame(getInfo.iloc[:, :])
    if info.empty:
        print('file is empty')
    else:
        print('file is not empty')
        for i in range(0, info.keys().size):
            if re.search('DUT.*Channel', info.keys()[i]):
                for j in range(0, len(info)):
                    m = re.split('_P', str(info.iat[j, i]))[0]
                    n = re.split('_P', str(info.iat[j, i]))[-1]

                    if (re.search('-P', n)):
                        p = re.findall('(.*?)-P', n)[0]
                        q = re.split('-P', n)[-1]
                        if (len(p) == 1):
                            p = '0' + p
                        if (len(q) == 1):
                            q = '0' + q
                        info.iat[j, i] = m + p + '-' + m + q
                    else:
                        if (len(n) == 1):
                            n = '0' + n
                        info.iat[j, i] = m + n
    fileTo = os.path.join(OutputPath, 'channel_map_'+Power+'.xlsx')
    info.to_excel(fileTo, header=1, index=False, encoding='utf-8', sheet_name=Power)

def getInfoOfUtlityChannel(path):
    getInfo = pd.read_excel(path, sheet_name=Utility, dtype=str, keep_default_na=False, header=1)
    info = pd.DataFrame(getInfo.iloc[:, :])
    if info.empty:
        print('file is empty')
    else:
        print('file is not empty')
        for i in range(0, info.keys().size):
            for j in range(0, len(info)):
                if re.search('_URW', info.iat[j, i]):
                    # print(str(info.iat[j, i]))
                    x = re.findall('UB(.*?)_URW', str(info.iat[j, i]))[0]
                    y = re.split('_URW', str(info.iat[j, i]))[-1]
                    if re.search('^0', y) and re.search('^((?!09).)*$', y):
                        y = '0' + str(int(y) + 1)
                        # print(y)
                    if re.search('^1\d', y) or re.search('09', y):
                        y = str(int(y) + 1)
                        # print("y---", y)
                    z = 'UT'+ x + y
                    info.iat[j, i] = z
        fileTo = os.path.join(OutputPath, 'channel_map_'+Utility+'.xlsx')
        info.to_excel(fileTo, header=1, index=False, encoding='utf-8', sheet_name=Utility)


Digital = '1826S_IO'
Power = '1826_PG'
Utility = 'CTRL'
path = os.path.join(os.getcwd(), 'input\\map.xlsx')
OutputPath = os.path.join(os.getcwd(), 'output')
# 判断是否存在output文件夹

if (os.path.exists(OutputPath)):
    shutil.rmtree(OutputPath)
    print('output dir has been rm -rf and new makedirs')
os.makedirs(OutputPath)

getInfoOfDigtalChannel(path)
getInfoOfDPSChannel(path)
getInfoOfUtlityChannel(path)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: Python可以使用open()函数读取txt文件,然后使用pandas库将数据写入Excel文件。 以下是一个示例代码: ```python import pandas as pd # 读取txt文件 with open('data.txt', 'r') as f: data = f.readlines() # 将数据转换为DataFrame df = pd.DataFrame([line.strip().split('\t') for line in data]) # 将数据写入Excel文件 df.to_excel('data.xlsx', index=False, header=False) ``` 其中,data.txt是要读取的txt文件,data.xlsx是要写入Excel文件。这个示例代码假设txt文件中的数据是以制表符分隔的。如果数据是以其他分隔符分隔的,需要相应地修改代码。 ### 回答2: Python可以轻松读取文本文件,并且可以将数据写入Excel文件中,使用Python处理文本和Excel文件是非常方便的。 读取txt文件 使用Python内置的open()函数打开需要读取的txt文本文件,并且使用read()方法读取整个文件内容,如下所示: ``` f = open('example.txt', 'r') content = f.read() f.close() ``` 读取的内容将存储在变量content中。其中,'example.txt'是需要读取的txt文件名,'r'表示以只读模式打开文件。 如果需要按行读取txt文件,可以使用readline()方法。例如: ``` f = open('example.txt', 'r') for line in f: print(line) f.close() ``` 此代码将打开example.txt文件,并在控制台中打印每一行。对于大型文本文件,这种方法比read()更有效。 写入Excel文件 Python中可以使用很多库来写入Excel文件,包括xlwt、openpyxl和xlutils等。在这里,我们将使用openpyxl库。 要使用openpyxl库,需要使用以下命令来安装它: ``` pip install openpyxl ``` 接下来,您可以使用以下代码创建一个新的Excel文件: ``` from openpyxl import Workbook wb = Workbook() ws = wb.active ws['A1'] = 'Hello' ws['B1'] = 'World!' wb.save('example.xlsx') ``` 此代码将创建一个名为example.xlsx的Excel文件,并将'Hello'和'World!'写入A1和B1单元格中。 要将txt文件中的数据写入Excel文件,可以使用以下代码: ``` from openpyxl import Workbook wb = Workbook() ws = wb.active f = open('example.txt', 'r') row = 1 for line in f: col = 1 for word in line.split(): ws.cell(row=row, column=col, value=word) col += 1 row += 1 f.close() wb.save('example.xlsx') ``` 此代码将打开example.txt,按行读取文件,并将每行中的单词写入Excel文件的单元格中。每行单词将占用Excel文件中的一行,并且将使用split()方法将行分割为单词。 在这里,我们根据读取的每个单元格的行和列号,使用ws.cell()方法将单词写入Excel文件中。最后保存Excel文件。 总结 Python读取txt文件并将数据写入Excel文件非常容易。Python提供了许多库和方法来处理文本和Excel文件。我们可以使用open()函数读取txt文本文件,并使用openpyxl库将数据写入Excel文件中。这种方法非常有效,并且可以处理大型文本和Excel文件。希望本文对大家有所帮助。 ### 回答3: Python是一种强大的编程语言,在数据处理和分析方面具有很大的优势。在数据处理过程中,通常需要将数据从不同的文件格式中转换。一个常见的操作是读取文本文件并将其转换为电子表格格式,这样可以更方便地对数据进行操作和分析。 Python可以通过使用一些库来实现将txt文件写入excel的操作。其中,最常用的库是pandas和openpyxl。 首先,使用pandas库将txt文件读取到pandas的DataFrame中: ``` import pandas as pd df = pd.read_csv('data.txt', delimiter="\t") ``` 这里使用read_csv函数读取txt文件。delimiter参数指定文件中的分隔符,并将文件内容读入一个DataFrame中。 接下来,使用openpyxl库将DataFrame对象写入excel文件中: ``` from openpyxl import Workbook book = Workbook() writer = pd.ExcelWriter('output.xlsx', engine='openpyxl') writer.book = book df.to_excel(writer, sheet_name='Sheet1') writer.save() ``` 在这里,使用openpyxl创建一个新的excel文件,并将它与pandas的ExcelWriter关联。ExcelWriter充当中间层,以帮助将DataFrame写入Excel文件。最后,将DataFrame对象写入到要输出的excel文件中。 以上就是Python读取txt文件并写入Excel的基本操作。当然,还可以使用更多的参数和方法来处理和操作数据。此外,还可以使用其他库,如xlwt和xlsxwriter,来实现相同的任务。需要根据实际需求选择适合的方法和工具。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值