将文件合并为一个Excel文件

问题描述 投票:0回答:1

我是python的新手,我想这是一个简单的任务。我有一堆测试数据的文本文件,我想合并为一个Excel文件,每个文件具有不同的工作表。我所能做的就是为每个文本文件制作单独的Excel文件。我尝试了很多方法将它们组合在一起,但是没有任何效果。我最忙的是制作带有不同图纸的Excel文件,但数据不会传输。任何帮助深表感谢。

下面是我正在阅读的文本文件的示例(/ t =制表符,/ n =新行,不在实际的文本文件中:]

测试人员名称:/ t名称测试日期:/ t 14/18/1900测试开始时间:/ t 00:00:00 PM测试结束时间:/ t 00:00:00 PM电压(V)/ t旋转位置(Deg)/ t力(N)

-0.031 / t 0.000 / t -0.030 / n-0.028 / t 0.000 / t -0.027 / n

下面是完整的代码,其中ClickProcessButton(self)部分已更新。我确实意识到许多导入对于此脚本都是无用的。

import numpy as np
import pandas as pd
from pandas import ExcelWriter
from pandas import ExcelFile
from pandas import Series
import xlwt
import xlrd
import os
import sys
from openpyxl import load_workbook
from openpyxl import Workbook
import openpyxl as xl
from tkinter import *
from tkinter import filedialog
from tkinter import ttk
from tkinter import messagebox
import tkinter as tk
import threading
import yaml
import sys
import os
import string
import datetime
import time
import openpyxl
import matplotlib.pyplot as plt
import csv
from select_files import select_files
from parse_data import parse_datafile
import chart_studio.plotly as py
import plotly.tools as tls
import plotly.graph_objs as go
import plotly.figure_factory as FF
from tkinter.filedialog import askopenfile
import xlsxwriter
from tkinter import *
from tkinter import filedialog
from tkinter import ttk
from tkinter import messagebox
import tkinter as tk



class Window(Frame):

    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.master = master

        # widget can take all window
        self.pack(fill=BOTH, expand=1)

        # create button, link it to clickExitButton()
        exitButton = Button(self, text="Exit", command=self.clickExitButton)
        exitButton.place(x=100, y=90)

        # create button, link it to clickProcessButton()
        processButton = Button(self, text="Process", command=self.clickProcessButton)
        processButton.place(x=100, y=10)

        # create button, link it to clickBrowseButton()
        browseButton = Button(self, text="Browse", command=self.clickBrowseButton)
        browseButton.place(x=100, y=50)


    def clickExitButton(self):
        exit()

    def clickBrowseButton(self):
        global dataFiles
        global rootdir

        rootdir = filedialog.askdirectory(title='Select Test Folder', initialdir=os.getcwd())



        #-#-#-#-#-#-#-#-#-#-#- Makes the folders if they do not exist -#-#-#-#-#-#-#-#-#-#-#
        try:
            os.mkdir(rootdir + "/Data")
            os.mkdir(rootdir + "/Plots")

        except FileExistsError:
            pass

    #-#-#-#-#-#-#-#-#-#-#- Processing the text files from Labview -#-#-#-#-#-#-#-#-#-#-#

    def clickProcessButton(self):

        col_names = ["", " ", "  "]

        #-#-#-#-#-#-#-#-#-#-#- Steps through each file in the directory -#-#-#-#-#-#-#-#-#-#-#
        for subdir, dirs, files in os.walk(rootdir):
            workbook = xlwt.Workbook()  # moved outside the loop

            for file in files:
                # using try and except to bypass xlsx files. if other file types are present other than .txt and .xlxs,
                # the script will not run
                try:
                    workFile = (os.path.join(subdir, file))
                    with open(workFile, 'r') as f:
                        fileName = file[18:]
                        fileName = fileName[:-4]

                        worksheet = workbook.add_worksheet('%s' % fileName)   #workbook.add_worksheet instead?
                        for row, line in enumerate(f):
                            line = line.rstrip()
                            for col, value in enumerate(line.split("\\t\\t")):
                                if is_number(value):
                                    worksheet.write(row, col, float(value), style=style)
                                else:
                                    worksheet.write(row, col, value)
                # except:
                #     pass
                except:
                    "*.xlsx" in file
            workbook.save('all_files.xlsx')

root = Tk()
app = Window(root)
root.wm_title("Tkinter button")
root.geometry("320x200")
root.mainloop()

此脚本在workbook.save('all_files.xlsx')行收到以下错误。错误是:IndexError:列表索引超出范围

python pandas xlsxwriter
1个回答
0
投票

您可以使用pandasExcelWriter创建所需的Excel输出。我假设您的文件存储在名为test

的文件夹中
import pandas as pd
import os

writer = pd.ExcelWriter('all_files.xlsx', engine='xlsxwriter')

for f in os.listdir('test'):

    header_info = pd.read_csv(os.path.join('test', f), sep=r'\t', engine='python', header=None, nrows=4)
    header_info.to_excel(writer, f, index=False, header=False)

    df = pd.read_csv(os.path.join('test', f), sep=r'\t', engine='python', header=4)
    df.to_excel(writer, f, startrow=5, index=False)

writer.save()
© www.soinside.com 2019 - 2024. All rights reserved.