CSV to JSON/XML Converter with Tkinter


Convert CSV to JSON or XML using Python

This tutorial shows you how to create an intuitive GUI application in Python using Tkinter. The application converts CSV files into JSON or XML format using Pandas. You will also learn how to save files using a file dialog and provide user feedback with interactive labels.


Convert CSV to JSON or XML with Tkinter and Pandas | Python GUI Tutorial #dataexport #dataimport

1. Importing Required Libraries


import tkinter as tk  # For GUI development
from tkinter import filedialog  # For file selection
import pandas as pd  # For CSV handling
import xml.etree.ElementTree as ET  # For XML conversion
  • Tkinter: Used for building GUI components like buttons and labels.
  • Pandas: Processes CSV data efficiently.
  • ElementTree: Converts data to XML format.

2. Browsing CSV Files


def browse_file():
    file_path = filedialog.askopenfilename(filetypes=[("CSV files", "*.csv")])
    if file_path:
        lbl_message.config(text=f"Selected File: {file_path}", bg="#d1f7c4")
    else:
        lbl_message.config(text="No file selected.", bg="#f8d7da")
  • Provides a dialog for selecting CSV files.
  • Displays the selected file path or an error message.

3. Converting to JSON or XML


def convert_file():
    if not csv_file_path:
        lbl_message.config(text="No file selected.", bg="#f8d7da")
        return
    
    output_format = option_var.get()
    save_path = filedialog.asksaveasfilename(defaultextension=f".{output_format.lower()}",
                                             filetypes=[(f"{output_format} files", f"*.{output_format.lower()}")])
    if not save_path:
        lbl_message.config(text="Save cancelled.", bg="#fff3cd")
        return
    
    try:
        df = pd.read_csv(csv_file_path)
        if output_format == "JSON":
            df.to_json(save_path, orient="records", indent=4)
        else:
            root = ET.Element("Root")
            for _, row in df.iterrows():
                row_elem = ET.SubElement(root, "Row")
                for col, val in row.items():
                    ET.SubElement(row_elem, col).text = str(val) if pd.notna(val) else ""
            ET.ElementTree(root).write(save_path, encoding="utf-8", xml_declaration=True)
        lbl_message.config(text=f"File saved: {save_path}", bg="#d1f7c4")
    except Exception as e:
        lbl_message.config(text=f"Error: {str(e)}", bg="#f8d7da")
  • JSON Conversion: Uses to_json for structured JSON output.
  • XML Conversion: Creates hierarchical XML using ElementTree.
  • Displays success or error messages dynamically.

4. Complete Code


import tkinter as tk
from tkinter import filedialog
import pandas as pd
import xml.etree.ElementTree as ET
import os

# Function to browse and select a CSV file
def browse_file():
    global csv_file_path
    csv_file_path = filedialog.askopenfilename(
        title="Select a CSV File",
        filetypes=(("CSV Files", "*.csv"), ("All Files", "*.*"))
    )
    if csv_file_path:
        update_message(f"Selected File: {csv_file_path}", bg="#d1f7c4")
    else:
        update_message("No file selected. Please select a CSV file.", bg="#f8d7da")

# Function to convert the selected CSV file to JSON or XML
def convert_file():
    if not csv_file_path or not os.path.exists(csv_file_path):
        update_message("Error: No valid CSV file selected!", bg="#f8d7da")
        return

    try:
        # Read the CSV file into a DataFrame
        df = pd.read_csv(csv_file_path)

        # Get user choice
        choice = option_var.get()
        save_path = filedialog.asksaveasfilename(
            title=f"Save as {choice}",
            defaultextension=f".{choice.lower()}",
            filetypes=((f"{choice} Files", f"*.{choice.lower()}"), ("All Files", "*.*"))
        )
        if not save_path:
            update_message("Save operation cancelled.", bg="#fff3cd")
            return

        if choice == "JSON":
            df.to_json(save_path, orient="records", indent=4)
            update_message(f"File saved as JSON at {save_path}", bg="#d1f7c4")
        elif choice == "XML":
            root_element = ET.Element("Root")
            for _, row in df.iterrows():
                row_element = ET.SubElement(root_element, "Row")
                for col_name, value in row.items():
                    col_element = ET.SubElement(row_element, col_name)
                    col_element.text = str(value)

            tree = ET.ElementTree(root_element)
            tree.write(save_path, encoding="utf-8", xml_declaration=True)
            update_message(f"File saved as XML at {save_path}", bg="#d1f7c4")
    except Exception as e:
        update_message(f"Error: {e}", bg="#f8d7da")

# Function to update the message label
def update_message(message, bg="#f0f8ff"):
    message_label.config(text=message, bg=bg)

# Main Window
root = tk.Tk()
root.title("CSV to JSON/XML Converter")

# UI Components
tk.Label(root, text="CSV to JSON/XML Converter", font=("Arial", 18, "bold")).pack(pady=10)

message_label = tk.Label(
    root, text="Select a CSV file to start.", font=("Arial", 12), bg="#f0f8ff", relief="sunken", width=50
)
message_label.pack(pady=10)

browse_button = tk.Button(root, text="Browse CSV File", command=browse_file)
browse_button.pack(pady=5)

option_var = tk.StringVar(value="JSON")
json_radio = tk.Radiobutton(root, text="Save as JSON", variable=option_var, value="JSON")
json_radio.pack(anchor="w", padx=20)

xml_radio = tk.Radiobutton(root, text="Save as XML", variable=option_var, value="XML")
xml_radio.pack(anchor="w", padx=20)

convert_button = tk.Button(root, text="Convert and Save", command=convert_file)
convert_button.pack(pady=10)

# Global variable for the file path
csv_file_path = None

# Run the application
root.geometry("500x400")
root.mainloop()

Using to_xml() to create xml file from DataFrame

Based on the selected option we go for creating xml file. Here is the code part to create xml file.

Original Code to Replace
elif choice == "XML":
    root_element = ET.Element("Root")
    for _, row in df.iterrows():
        row_element = ET.SubElement(root_element, "Row")
        for col_name, value in row.items():
            col_element = ET.SubElement(row_element, col_name)
            col_element.text = str(value)

    tree = ET.ElementTree(root_element)
    tree.write(save_path, encoding="utf-8", xml_declaration=True)
    update_message(f"File saved as XML at {save_path}", bg="#d1f7c4")
Updated Code Using to_xml()
elif choice == "XML":
    df.to_xml(save_path, index=False, root_name="Root", row_name="Row")
    update_message(f"File saved as XML at {save_path}", bg="#d1f7c4")
Export SQLite database table data to CSV file by using Dataframe
Tkinter Projects Projects Tkinter using Pandas DataFrame


Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer