def bookImport(fileName=None): """Import data from text file into book.""" fileName = GPath(fileName) init(3) data = {} # --Import from book textPath = GPath(fileName.root() + ".csv") ins = textPath.open() ins.readline() # --Skip first line for line in ins: line = line.strip() if not line or "\t" not in line: return (eid, full, value) = line.split("\t")[:3] eid = eid[1:-1] full = full[1:-1] value = int(value) # print eid,full,value data[eid] = value ins.close() # --Export to book modInfo = bosh.modInfos[fileName] loadFactory = bosh.LoadFactory(True, bosh.MreBook) modFile = bosh.ModFile(modInfo, loadFactory) modFile.load(True) for book in modFile.BOOK.records: if book.eid in data: print "%-35s %3d %3d" % (book.eid, book.value, data[book.eid]) book.value = data[book.eid] book.setChanged() else: print book.eid, "NOT----------" modFile.safeSave()
def bookExport(fileName=None): """Export data from book to text file(s).""" fileName = GPath(fileName) init(3) # --Data from mod doImport = True modInfo = bosh.modInfos[fileName] loadFactory = bosh.LoadFactory(doImport, bosh.MreBook) modFile = bosh.ModFile(modInfo, loadFactory) modFile.load(True) data = {} texts = {} imported = {} # --Import Book texts if doImport: eid = None buffer = None reAt = re.compile("^@", re.M) reHeader = re.compile("== ?\[(\w+)\]") ins = GPath(fileName.root() + ".txt").open("r") reEndLine = re.compile("\n") for line in ins: maHeader = reHeader.match(line) if maHeader: if eid and buffer: imported[eid] = bosh.winNewLines(buffer.getvalue()) eid = maHeader.group(1) buffer = cStringIO.StringIO() addTags = True wasBlank = True firstLine = True blanks = "" elif buffer: if firstLine: firstLine = False addTags = "<" not in line if addTags: line = '<font face=1><div align="center">' + line isBlank = not bool(line.strip()) if addTags: line = reAt.sub('<div align="left">', line) line = reEndLine.sub("<br>\n", line) if isBlank: blanks += line else: buffer.write(blanks) buffer.write(line) blanks = "" ins.close() if eid and buffer: imported[eid] = bosh.winNewLines(buffer.getvalue()) # --Books from mod changed = False for book in modFile.BOOK.records: if doImport: newText = imported.get(book.eid) if newText and newText != book.text: print "Updating", book.eid book.text = newText book.setChanged() changed = True data[book.eid] = (book.eid, book.full, book.value, len(book.text)) texts[book.eid] = book.text # --Save import? if doImport and changed: modFile.askSave(True) # --Dump book info if False: textPath = GPath(fileName.root() + ".csv") out = textPath.open("w") # out.write('"Edit Id"\t"Name"\t"Value"\t"Text Len"\n') for eid in sorted(data): out.write('"%s"\t"%s"\t"%d"\t"%d"\n' % data[eid]) out.close() # --Dump Texts if True: reNewLine = re.compile("\r\n") out = GPath(fileName.root() + ".txt").open("w") for eid in sorted(data): text = reNewLine.sub("\n", texts[eid]) out.write("== [%s] %s\n" % data[eid][:2]) out.write(text) out.write("\n\n") out.close()