Skip to content

Instantly share code, notes, and snippets.

@lidio601
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lidio601/8376970e0cded5be1f12 to your computer and use it in GitHub Desktop.
Save lidio601/8376970e0cded5be1f12 to your computer and use it in GitHub Desktop.
Split MySQL DB Dump file. I needed a script to get a MySQL database dump given by the PHPMyAdmin dbms and split it up in different .sql files, one for each SQL Database.
#!/usr/sbin/python
#encoding=utf8
import string, os, sys
SEPARATOR = """-- Current Database: `"""
def sep(str0):
if not str0.startswith(SEPARATOR) and SEPARATOR in str0:
return (str0,'','')
return str0.partition(SEPARATOR)
header_gone = False
header = ''
a = ''
b = ''
basepath = '/'
fpout = None
def apri(line):
global fpout
if fpout:
fpout.flush()
fpout.close()
t0 = line.partition(SEPARATOR)
t1 = t0[2].partition("`")
nome = t1[0]+".sql"
dest = os.path.join( basepath, nome )
if os.path.exists(dest):
fpout = open(dest,'a')
else:
print "Scrivo il file", dest
fpout = open(dest,'w')
scrivi(header)
scrivi(line)
def scrivi(line):
global fpout
fpout.write(line)
def dowork(filein):
global header_gone
global header
global a
global b
global fpout
global basepath
header_gone = False
header = ''
a = ''
b = ''
fpout = None
basepath = os.path.join(os.path.dirname(filein),'split')
print "Directory base: ", basepath
if not os.path.exists(basepath):
os.mkdir(basepath)
fp = open(filein, 'r')
if fp == None:
print 'Impossibile aprire il file ', filein
return
temp = fp.readline()
while len(temp) > 0 :
a,t,b = sep(temp)
if not header_gone:
if len(b)>0:
# ho trovato il primo separatore,
# quindi l'header è finito
header_gone = True
# apro il primo file da esportare
header = header + a
apri(t+b)
else:
# ho tutto un pezzo di header in <a>
# lo segno nella variabili header
header = header + a
else:
if len(b)>0:
# ho trovato il separatore, passo al file successivo
scrivi(a)
apri(t+b)
else:
# sono ancora nel file che avevo iniziato, scrivo a
scrivi(a)
temp = fp.readline()
fp.close()
if fpout != None:
fpout.flush()
fpout.close()
if __name__ == '__main__':
if len(sys.argv) >= 2:
print "Apro il file:", sys.argv[1]
dowork(sys.argv[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment