Created
October 26, 2019 21:46
-
-
Save HeshamMeneisi/df9e77a36316a715824a2a0cfbc97bdb to your computer and use it in GitHub Desktop.
ACCDB to CSV on non-Windows system (Without MS Access parser)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# coding: utf-8 | |
# Requirements | |
# sudo apt install mdbtools | |
import os | |
import subprocess | |
def runShellCMD(cmd): | |
MyOut = subprocess.Popen(cmd, | |
stdout=subprocess.PIPE, | |
stderr=subprocess.PIPE, | |
shell=True) | |
stdout,stderr = MyOut.communicate() | |
stdout = stdout.decode('utf8') | |
stderr = stderr.decode('utf8') | |
return stdout, stderr | |
def accdbGetTables(fname): | |
stdout, stderr = runShellCMD("mdb-tables '%s'" % fname) | |
if stderr != '': | |
print(stderr) | |
return None | |
else: | |
return stdout.strip().split("\n") | |
def cleanPath(path): | |
keepcharacters = (' ', '.','_') | |
return "".join(c for c in path if c.isalnum() or c in keepcharacters).rstrip() | |
def accdbToCSV(fname, dest_dir=None): | |
tables = accdbGetTables(fname) | |
if tables: | |
csvs = [] | |
if dest_dir is None: | |
dest_dir = os.path.dirname(fname) | |
for table in tables: | |
csv_fname = os.path.splitext(fname)[0]+"_%s.csv"%(table) | |
csv_fname = cleanPath(csv_fname).replace(' ', '_') | |
csv_fname = os.path.join(dest_dir, csv_fname) | |
print("Converting ['%s' > '%s'] to '%s'" % (fname, table, csv_fname)) | |
stdout, stderr = runShellCMD("mdb-export '%s' '%s' >'%s'" % (fname, table, csv_fname)) | |
if stderr != '': | |
print(stderr) | |
else: | |
csvs.append(csv_fname) | |
return csvs | |
else: | |
return None | |
# Example | |
# print(accdbToCSV("test.accdb")) | |
# Output should be a list of CSV file paths, one per table |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment