将文件合并为一个 Excel 文件

Consolidating files into one Excel file

我是 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:列表索引超出范围

您可以使用 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()