-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsplitter-v1.py
More file actions
195 lines (152 loc) · 8.25 KB
/
Copy pathsplitter-v1.py
File metadata and controls
195 lines (152 loc) · 8.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
import csv
import os
from pathlib import Path
class CSVSplitterApp:
def __init__(self, root):
self.root = root
self.root.title("CSV Splitter")
self.root.geometry("600x500")
self.root.configure(bg="#f0f0f0")
self.style = ttk.Style()
self.style.theme_use("clam")
self.style.configure("TFrame", background="#f0f0f0")
self.style.configure("TLabel", background="#f0f0f0", font=("Arial", 10))
self.style.configure("TButton", font=("Arial", 10), padding=6)
self.style.configure("Horizontal.TProgressbar", thickness=20)
self.file_path = tk.StringVar()
self.chunk_size = tk.IntVar(value=40)
self.include_header = tk.BooleanVar(value=True)
self.output_dir = tk.StringVar()
self.create_widgets()
def create_widgets(self):
main_frame = ttk.Frame(self.root, padding="20")
main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
title_label = ttk.Label(main_frame, text="CSV Splitter", font=("Arial", 16, "bold"))
title_label.grid(row=0, column=0, columnspan=3, pady=(0, 20))
ttk.Label(main_frame, text="Select CSV File:").grid(row=1, column=0, sticky=tk.W, pady=5)
file_frame = ttk.Frame(main_frame)
file_frame.grid(row=2, column=0, columnspan=3, sticky=(tk.W, tk.E), pady=5)
ttk.Entry(file_frame, textvariable=self.file_path, width=50, state="readonly").grid(row=0, column=0, sticky=(tk.W, tk.E), padx=(0, 10))
ttk.Button(file_frame, text="Browse", command=self.browse_file).grid(row=0, column=1)
file_frame.columnconfigure(0, weight=1)
settings_frame = ttk.LabelFrame(main_frame, text="Settings", padding="10")
settings_frame.grid(row=3, column=0, columnspan=3, sticky=(tk.W, tk.E), pady=15)
ttk.Label(settings_frame, text="Chunk Size:").grid(row=0, column=0, sticky=tk.W, pady=5)
chunk_frame = ttk.Frame(settings_frame)
chunk_frame.grid(row=0, column=1, sticky=tk.W, pady=5)
ttk.Spinbox(chunk_frame, from_=1, to=1000, textvariable=self.chunk_size, width=10).grid(row=0, column=0)
ttk.Label(chunk_frame, text="rows").grid(row=0, column=1, padx=(5, 0))
ttk.Checkbutton(settings_frame, text="Include Header in Each Chunk", variable=self.include_header).grid(row=1, column=0, columnspan=2, sticky=tk.W, pady=5)
ttk.Label(settings_frame, text="Output Directory:").grid(row=2, column=0, sticky=tk.W, pady=(10, 5))
output_frame = ttk.Frame(settings_frame)
output_frame.grid(row=3, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=5)
ttk.Entry(output_frame, textvariable=self.output_dir, width=50, state="readonly").grid(row=0, column=0, sticky=(tk.W, tk.E), padx=(0, 10))
ttk.Button(output_frame, text="Browse", command=self.browse_output_dir).grid(row=0, column=1)
output_frame.columnconfigure(0, weight=1)
settings_frame.columnconfigure(1, weight=1)
button_frame = ttk.Frame(main_frame)
button_frame.grid(row=4, column=0, columnspan=3, pady=20)
self.split_button = ttk.Button(button_frame, text="Split CSV", command=self.split_csv, state="disabled")
self.split_button.grid(row=0, column=0, padx=5)
ttk.Button(button_frame, text="Reset", command=self.reset_form).grid(row=0, column=1, padx=5)
self.progress = ttk.Progressbar(main_frame, orient="horizontal", mode="determinate", style="Horizontal.TProgressbar")
self.progress.grid(row=5, column=0, columnspan=3, sticky=(tk.W, tk.E), pady=10)
self.status_label = ttk.Label(main_frame, text="", font=("Arial", 9))
self.status_label.grid(row=6, column=0, columnspan=3, pady=5)
self.root.columnconfigure(0, weight=1)
self.root.rowconfigure(0, weight=1)
main_frame.columnconfigure(0, weight=1)
main_frame.rowconfigure(6, weight=1)
def browse_file(self):
filename = filedialog.askopenfilename(
title="Select CSV file",
filetypes=[("CSV files", "*.csv"), ("All files", "*.*")]
)
if filename:
self.file_path.set(filename)
if not self.output_dir.get():
self.output_dir.set(os.path.dirname(filename))
self.split_button.config(state="normal")
def browse_output_dir(self):
directory = filedialog.askdirectory(title="Select Output Directory")
if directory:
self.output_dir.set(directory)
def split_csv(self):
if not self.file_path.get():
messagebox.showerror("Error", "Please select a CSV file")
return
if not self.output_dir.get():
messagebox.showerror("Error", "Please select an output directory")
return
try:
self.split_button.config(state="disabled")
self.status_label.config(text="Processing...")
self.root.update()
self._split_csv_process()
self.status_label.config(text="Splitting completed successfully!")
messagebox.showinfo("Success", "CSV file has been split successfully!")
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {str(e)}")
self.status_label.config(text="Error occurred")
finally:
self.split_button.config(state="normal")
def _split_csv_process(self):
input_file = self.file_path.get()
chunk_size = self.chunk_size.get()
include_header = self.include_header.get()
output_dir = self.output_dir.get()
Path(output_dir).mkdir(parents=True, exist_ok=True)
base_filename = os.path.splitext(os.path.basename(input_file))[0]
with open(input_file, 'r', newline='', encoding='utf-8') as csvfile:
reader = csv.reader(csvfile)
header = None
if include_header:
try:
header = next(reader)
except StopIteration:
messagebox.showwarning("Warning", "CSV file is empty")
return
csvfile.seek(0)
total_rows = sum(1 for row in csvfile) - (1 if include_header else 0)
csvfile.seek(0)
if include_header:
next(csvfile)
self.progress['maximum'] = total_rows
processed_rows = 0
chunk_num = 1
writer = None
output_file = None
for i, row in enumerate(reader):
if i % chunk_size == 0:
if output_file:
output_file.close()
chunk_filename = f"{base_filename}_part_{chunk_num}.csv"
chunk_filepath = os.path.join(output_dir, chunk_filename)
output_file = open(chunk_filepath, 'w', newline='', encoding='utf-8')
writer = csv.writer(output_file)
if include_header and header:
writer.writerow(header)
chunk_num += 1
writer.writerow(row)
processed_rows += 1
if processed_rows % 10 == 0 or processed_rows == total_rows:
self.progress['value'] = processed_rows
self.status_label.config(text=f"Processing... ({processed_rows}/{total_rows} rows)")
self.root.update_idletasks()
if output_file:
output_file.close()
self.progress['value'] = total_rows
def reset_form(self):
self.file_path.set("")
self.chunk_size.set(40)
self.include_header.set(True)
self.output_dir.set("")
self.progress['value'] = 0
self.status_label.config(text="")
self.split_button.config(state="disabled")
if __name__ == "__main__":
root = tk.Tk()
app = CSVSplitterApp(root)
root.mainloop()