Untitled

 avatar
unknown
python
2 years ago
1.1 kB
5
Indexable
import sqlite3
import csv

# Replace 'your_realm_file.realm' with the actual Realm file name
realm_file = 'your_realm_file.realm'

# Connect to SQLite (Realm files can be treated as SQLite databases)
connection = sqlite3.connect(realm_file)
cursor = connection.cursor()

# Get the list of tables (objects) in the Realm file
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
tables = cursor.fetchall()

# Loop through each table and export data to CSV
for table in tables:
    table_name = table[0]
    
    # Fetch data from the SQLite table
    cursor.execute('SELECT * FROM {}'.format(table_name))
    data = cursor.fetchall()

    # Write data to a CSV file
    csv_file = '{}.csv'.format(table_name)
    with open(csv_file, 'w', newline='') as csvfile:
        csv_writer = csv.writer(csvfile)
        # Write header
        csv_writer.writerow([description[0] for description in cursor.description])
        # Write data
        csv_writer.writerows(data)

    print('Data exported from {} to {}'.format(table_name, csv_file))

# Close the SQLite connection
connection.close()
Editor is loading...
Leave a Comment