Universal File Converter Python GUI
👤 Sharing: AI
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
import os
import json
import csv
class UniversalFileConverter:
def __init__(self, master):
self.master = master
master.title("Universal File Converter")
self.input_file = tk.StringVar()
self.output_file = tk.StringVar()
self.conversion_type = tk.StringVar()
# Input File
tk.Label(master, text="Input File:").grid(row=0, column=0, sticky=tk.W, padx=5, pady=5)
self.input_entry = tk.Entry(master, textvariable=self.input_file, width=50)
self.input_entry.grid(row=0, column=1, sticky=tk.W, padx=5, pady=5)
self.input_button = tk.Button(master, text="Browse", command=self.browse_input)
self.input_button.grid(row=0, column=2, sticky=tk.W, padx=5, pady=5)
# Output File
tk.Label(master, text="Output File:").grid(row=1, column=0, sticky=tk.W, padx=5, pady=5)
self.output_entry = tk.Entry(master, textvariable=self.output_file, width=50)
self.output_entry.grid(row=1, column=1, sticky=tk.W, padx=5, pady=5)
self.output_button = tk.Button(master, text="Browse", command=self.browse_output)
self.output_button.grid(row=1, column=2, sticky=tk.W, padx=5, pady=5)
# Conversion Type
tk.Label(master, text="Conversion Type:").grid(row=2, column=0, sticky=tk.W, padx=5, pady=5)
self.conversion_combo = ttk.Combobox(master, textvariable=self.conversion_type,
values=["JSON to CSV", "CSV to JSON", "Text to JSON", "JSON to Text"])
self.conversion_combo.grid(row=2, column=1, sticky=tk.W, padx=5, pady=5)
self.conversion_combo.set("JSON to CSV") # Default value
# Convert Button
self.convert_button = tk.Button(master, text="Convert", command=self.convert_file)
self.convert_button.grid(row=3, column=1, sticky=tk.E, padx=5, pady=10)
# Details Button
self.details_button = tk.Button(master, text="Details", command=self.show_details)
self.details_button.grid(row=3, column=0, sticky=tk.W, padx=5, pady=10)
def browse_input(self):
filename = filedialog.askopenfilename()
self.input_file.set(filename)
def browse_output(self):
filename = filedialog.asksaveasfilename(defaultextension=".txt") # Default extension
self.output_file.set(filename)
def convert_file(self):
input_file = self.input_file.get()
output_file = self.output_file.get()
conversion_type = self.conversion_type.get()
if not input_file or not output_file or not conversion_type:
messagebox.showerror("Error", "Please fill in all fields.")
return
try:
if conversion_type == "JSON to CSV":
with open(input_file, 'r') as f:
data = json.load(f)
if isinstance(data, list):
# Assuming each element in the list is a dictionary
keys = data[0].keys() if data else [] # get keys from first dict
with open(output_file, 'w', newline='') as f:
dict_writer = csv.DictWriter(f, keys)
dict_writer.writeheader()
dict_writer.writerows(data)
elif isinstance(data, dict):
# if json data is a dict and not a list of dicts
keys = data.keys()
with open(output_file, 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(keys)
writer.writerow(data.values())
else:
messagebox.showerror("Error", "Invalid JSON format for CSV conversion. Must be list of dictionaries or a dictionary.")
return
elif conversion_type == "CSV to JSON":
with open(input_file, 'r') as f:
reader = csv.DictReader(f)
data = list(reader)
with open(output_file, 'w') as f:
json.dump(data, f, indent=4)
elif conversion_type == "Text to JSON":
with open(input_file, 'r') as f:
text_data = f.read()
# Simple conversion - assumes text needs to be in a JSON structure.
# For more complex cases, you'd need more sophisticated parsing.
data = {"text": text_data}
with open(output_file, 'w') as f:
json.dump(data, f, indent=4)
elif conversion_type == "JSON to Text":
with open(input_file, 'r') as f:
data = json.load(f)
# Simple conversion - assumes text needs to be extracted from JSON structure.
# Adapt based on the specific JSON structure
if isinstance(data, dict) and "text" in data:
text_data = data["text"]
else:
text_data = str(data)
with open(output_file, 'w') as f:
f.write(text_data)
messagebox.showinfo("Success", "File converted successfully!")
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {e}")
def show_details(self):
messagebox.showinfo("Details", "This Universal File Converter is a versatile tool designed to convert between various file formats, including JSON, CSV, and plain text. It provides a user-friendly GUI for selecting input and output files, as well as specifying the desired conversion type. It currently supports conversion between JSON, CSV and TXT. The implementation uses standard library modules like json and csv for efficient file handling. The Text to JSON conversion creates a simple JSON structure. The JSON to Text extraction will only work if the JSON has a key 'text'. The application handles errors gracefully and provides informative messages to the user.")
root = tk.Tk()
converter = UniversalFileConverter(root)
root.mainloop()
👁️ Viewed: 9
Comments