Консолидация файлов в один файл Excel - PullRequest
0 голосов
/ 28 февраля 2020

Я прилично новичок в python, и я думаю, что это простая задача. У меня есть куча текстовых файлов с тестовыми данными, которые я хочу объединить в один файл Excel с различными листами для каждого файла. Все, что мне удалось сделать sh, - это создать отдельные файлы Excel для каждого текстового файла. Я пробовал много способов объединить их, но ничего не помогло. Максимум, что мне удалось - это создать файл Excel с разными листами, но данные не передаются. Буду признателен за любую оказанную помощь.

Ниже приведен пример текстовых файлов, которые я читаю (/ t = tab, / n = новая строка, но не в текстовом файле):

Имя тестера: / t name
Дата испытания: / t 14/18/1900
Время начала испытания: / t 00:00:00 PM
Время окончания испытания: / t 00:00:00 PM
Напряжение (В ) / т Поворотное положение (град) / т Усилие (Н)

-0,031 / т 0,000 / т -0,030 / n
-0,028 / т 0,000 / т -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: список индексов вне диапазона

1 Ответ

0 голосов
/ 28 февраля 2020

Вы можете использовать pandas и ExcelWriter для создания желаемого вывода в 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()
...