Here is a Python GUI application using tkinter and pandas that fulfills your requirements:
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
import pandas as pd
import os
import glob
class CSVCombinerApp:
def __init__(self, master):
self.master = master
master.title("CSV Combiner App")
self.folder_path = tk.StringVar()
# Folder selection
self.label = tk.Label(master, text="Select Folder:")
self.label.grid(row=0, column=0, padx=10, pady=5, sticky='e')
self.entry = tk.Entry(master, textvariable=self.folder_path, width=50)
self.entry.grid(row=0, column=1, padx=10, pady=5)
self.browse_button = tk.Button(master, text="Browse", command=self.browse_folder)
self.browse_button.grid(row=0, column=2, padx=10, pady=5)
# Summarization Level
self.summary_label = tk.Label(master, text="Summarize by:")
self.summary_label.grid(row=1, column=0, padx=10, pady=5, sticky='e')
self.summary_option = tk.StringVar()
self.summary_option.set("Hour")
self.summary_combobox = ttk.Combobox(master, textvariable=self.summary_option, values=["Hour", "Minute"], state="readonly")
self.summary_combobox.grid(row=1, column=1, padx=10, pady=5, sticky='w')
# Start Button
self.start_button = tk.Button(master, text="Start Processing", command=self.start_processing)
self.start_button.grid(row=2, column=1, padx=10, pady=20)
def browse_folder(self):
folder_selected = filedialog.askdirectory()
if folder_selected:
self.folder_path.set(folder_selected)
def start_processing(self):
folder = self.folder_path.get()
summary_by = self.summary_option.get()
if not folder:
messagebox.showerror("Error", "Please select a folder.")
return
try:
# Process CSV files
combined_df = self.process_csv_files(folder)
if combined_df.empty:
messagebox.showinfo("No Data", "No data was processed.")
return
# Summarize data
summarized_df = self.summarize_data(combined_df, summary_by)
# Output CSV file
output_file = os.path.join(folder, 'combined_output.csv')
summarized_df.to_csv(output_file, index=False)
messagebox.showinfo("Success", f"Processing complete! Output file saved to:\n{output_file}")
except Exception as e:
messagebox.showerror("Error", str(e))
def process_csv_files(self, folder):
all_files = []
# Use glob to find all CSV files recursively
for root, dirs, files in os.walk(folder):
csv_files = glob.glob(os.path.join(root, '*.csv'))
all_files.extend(csv_files)
data_frames = []
for file in all_files:
# Read CSV starting from line 45 (skip first 44 rows)
df = pd.read_csv(file, skiprows=44, encoding='utf-8', header=None)
# Ignore files with less than 12 columns
if df.shape[1] < 12:
continue
# Pick predefined columns (adjust indices as per your requirement)
predefined_columns = [0, 1, 2, 3] # Example column indices
df = df.iloc[:, predefined_columns]
data_frames.append(df)
if data_frames:
combined_df = pd.concat(data_frames, ignore_index=True)
return combined_df
else:
return pd.DataFrame()
def summarize_data(self, df, summary_by):
# Assuming one of the selected columns is a datetime column
# Let's assume the first column is datetime
df.columns = ['DateTime', 'Col2', 'Col3', 'Col4'] # Adjust column names as needed
# Convert to datetime
df['DateTime'] = pd.to_datetime(df['DateTime'], errors='coerce')
df = df.dropna(subset=['DateTime'])
if summary_by == 'Hour':
df['Time_Group'] = df['DateTime'].dt.floor('H')
elif summary_by == 'Minute':
df['Time_Group'] = df['DateTime'].dt.floor('T')
# Group and summarize
summarized_df = df.groupby('Time_Group').agg({'Col2': 'sum', 'Col3': 'mean'}) # Adjust aggregations as needed
summarized_df = summarized_df.reset_index()
return summarized_df
if __name__ == '__main__':
root = tk.Tk()
app = CSVCombinerApp(root)
root.mainloop()
Instructions:
-
Select a Folder:
- Click the "Browse" button to select the folder containing your CSV files. The application will include all CSV files in the selected folder and its subfolders.
-
Summarization Level:
- Choose between "Hour" or "Minute" summarization from the dropdown menu.
-
Start Processing:
- Click the "Start Processing" button to begin reading and combining the CSV files.
- The application will read each CSV file starting from line 45, ignore files with less than 12 columns, and pick predefined columns (adjustable in the code).
-
Output:
- The combined and summarized data will be saved as
combined_output.csv in the selected folder.
- A message box will inform you when processing is complete.
Customization:
Notes:
- The application handles Japanese text by specifying
encoding='utf-8' when reading the CSV files.
- It skips the first 44 rows (
skiprows=44) to start reading from line 45.
- Make sure the datetime column is correctly identified and formatted for accurate summarization.
- Ensure you have the required Python packages installed (
tkinter, pandas).
Dependencies Installation:
If you haven't installed pandas yet, you can install it using:
pip install pandas
Running the Application:
Save the code to a file named, for example, csv_combiner_app.py, and run it using:
python csv_combiner_app.py
Visual Interface:
The GUI is straightforward, with options to select the folder, choose the summarization level, and start processing:
- Select Folder: Allows you to navigate and select the folder containing the CSV files.
- Summarize by: Dropdown menu to choose between summarizing by hour or minute.
- Start Processing: Initiates the CSV reading, combining, and summarizing process.
Error Handling:
- If no folder is selected, an error message will prompt you to select one.
- If an exception occurs during processing, it will be displayed in an error message box.
Feel free to customize and extend the application according to your specific needs. If you have any questions or need further assistance, please let me know!