This content originally appeared on DEV Community and was authored by RUDRA SHARMA
import os
import pandas as pd
def convert_excel_to_csv(folder_path):
# Traverse through folders and subfolders
for root, dirs, files in os.walk(folder_path):
for file in files:
if file.endswith((".xlsx", ".xls")): # Detect Excel files
excel_path = os.path.join(root, file)
try:
print(f"Processing {excel_path}")
# Load the Excel file
excel_file = pd.ExcelFile(excel_path)
# Iterate through each sheet
for sheet_name in excel_file.sheet_names:
# Read the sheet into a DataFrame
df = excel_file.parse(sheet_name)
# Define the CSV filename
csv_filename = f"{os.path.splitext(file)[0]}_{sheet_name}.csv"
csv_path = os.path.join(root, csv_filename) # Save CSV in the same directory as the Excel file
# Save the DataFrame as a CSV file
df.to_csv(csv_path, index=False)
print(f"Saved: {csv_path}")
except Exception as e:
print(f"Error processing {excel_path}: {e}")
# Provide the directory path where the script should start
run_directory = os.getcwd() # Use current working directory
convert_excel_to_csv(run_directory)
This content originally appeared on DEV Community and was authored by RUDRA SHARMA