【问题标题】:Consolidating files into one Excel file将文件合并为一个 Excel 文件
【发布时间】:2020-06-12 05:10:56
【问题描述】:

我对 python 很陌生,我想这是一个简单的任务。我有一堆测试数据的文本文件,我想将它们合并到一个 Excel 文件中,每个文件都有不同的工作表。我所能完成的就是为每个文本文件制作单独的 Excel 文件。我尝试了很多方法来组合它们,但没有任何效果。我管理的最多的是用不同的工作表制作一个 Excel 文件,但数据没有传输。 任何帮助深表感谢。

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

测试者姓名:/t name
测试日期:/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 : list index out of range

【问题讨论】:

  • 每个文件的工作表是否相同?相同的列数?相同的列名?
  • 每个文件的工作表名称不同,列数相同,行数长度不同。我的列名都一样。 Brajanna 我正在尝试提供的链接中的解决方案,并将报告

标签: python pandas xlsxwriter


【解决方案1】:

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

【讨论】:

  • 感谢 rahlf23 的回复!该脚本似乎适用于标题,但不适用于文本正文。我收到 ParseError: pandas.errors.ParserError: Expected 2 fields in line 46, saw 4. 错误可能是由于使用多字符定界符时忽略引号引起的。不确定它在文件中的读取方式会有所不同吗?当我为每个文本生成我的单个 excel 文件并且没有收到这个文件之前,我正在使用 pandas。目前正在寻找解决方案
  • 能够让代码最终运行。不确定到底有什么不同,但它现在正在处理文件。再次感谢!
  • 当然,很乐意提供帮助!
猜你喜欢
  • 1970-01-01
  • 2015-01-12
  • 2020-12-16
  • 1970-01-01
  • 2022-11-09
  • 2016-12-28
  • 1970-01-01
  • 2020-08-05
  • 1970-01-01
相关资源
最近更新 更多