Just wrapping the script in a [code]....[/code] block for clarity
Quote:
Originally Posted by Bill Overal
Code:
import xml.etree.ElementTree as ET
import os
def opf_to_enw(opf_path):
try:
tree = ET.parse(opf_path)
root = tree.getroot()
ns = {
'dc': 'http://purl.org/dc/elements/1.1/',
'opf': 'http://www.idpf.org/2007/opf'
}
title = root.find('.//dc:title', ns)
creators = root.findall('.//dc:creator', ns)
publisher = root.find('.//dc:publisher', ns)
date = root.find('.//dc:date', ns)
identifiers = root.findall('.//dc:identifier', ns)
author_lines = [f"%A {c.text.strip()}" for c in creators if c.text]
isbn = None
for ident in identifiers:
text = ident.text.strip() if ident.text else ''
if len(text) in [10, 13] and text.isdigit():
isbn = text
if len(text) == 13:
break
enw_lines = ['%0 Book']
if title is not None and title.text:
enw_lines.append(f"%T {title.text.strip()}")
enw_lines.extend(author_lines)
if date is not None and date.text:
enw_lines.append(f"%D {date.text.strip()}")
if publisher is not None and publisher.text:
enw_lines.append(f"%I {publisher.text.strip()}")
if isbn:
enw_lines.append(f"%@ {isbn}")
# Save file with same base name
enw_path = opf_path.replace('.opf', '.enw')
with open(enw_path, 'w', encoding='utf-8') as f:
f.write('\n'.join(enw_lines) + '\n')
print(f"✔ Converted: {os.path.basename(opf_path)}")
except Exception as e:
print(f"✘ Error processing {opf_path}: {e}")
if __name__ == "__main__":
folder = os.path.dirname(os.path.abspath(__file__))
print(f" Processing .opf files in folder: {folder}\n")
for file in os.listdir(folder):
if file.lower().endswith('.opf'):
opf_to_enw(os.path.join(folder, file))
print("\n✅ Done. .enw files saved in the same folder.")
input("\nPress Enter to close.")
|