diff --git a/src/calibre/ebooks/conversion/plugins/comic_input.py b/src/calibre/ebooks/conversion/plugins/comic_input.py index 13301d96f8..216b1e046b 100644 --- a/src/calibre/ebooks/conversion/plugins/comic_input.py +++ b/src/calibre/ebooks/conversion/plugins/comic_input.py @@ -102,7 +102,8 @@ class ComicInput(InputFormatPlugin): '%s is not a valid comic collection' ' no comics.txt was found in the file') %stream.name) - raw = open('comics.txt', 'rb').read() + with open('comics.txt', 'rb') as f: + raw = f.read() if raw.startswith(codecs.BOM_UTF16_BE): raw = raw.decode('utf-16-be')[1:] elif raw.startswith(codecs.BOM_UTF16_LE): @@ -230,8 +231,8 @@ class ComicInput(InputFormatPlugin): _('Page')+' %d'%(i+1), play_order=po) po += 1 opf.set_toc(toc) - m, n = open(u'metadata.opf', 'wb'), open('toc.ncx', 'wb') - opf.render(m, n, u'toc.ncx') + with open(u'metadata.opf', 'wb') as m, open('toc.ncx', 'wb') as n: + opf.render(m, n, u'toc.ncx') return os.path.abspath(u'metadata.opf') def create_wrappers(self, pages): diff --git a/src/calibre/ebooks/conversion/plugins/epub_output.py b/src/calibre/ebooks/conversion/plugins/epub_output.py index 7af7f9ed4c..81eb576b59 100644 --- a/src/calibre/ebooks/conversion/plugins/epub_output.py +++ b/src/calibre/ebooks/conversion/plugins/epub_output.py @@ -367,7 +367,8 @@ class EPUBOutput(OutputFormatPlugin): if tag.tail: tag.tail = tag.tail.strip() compressed = etree.tostring(tree.getroot(), encoding='utf-8') - open(ncx_path, 'wb').write(compressed) + with open(ncx_path, 'wb') as f: + f.write(compressed) # }}} def workaround_ade_quirks(self): # {{{ diff --git a/src/calibre/ebooks/conversion/plugins/html_output.py b/src/calibre/ebooks/conversion/plugins/html_output.py index ba2e922267..8ce728c98e 100644 --- a/src/calibre/ebooks/conversion/plugins/html_output.py +++ b/src/calibre/ebooks/conversion/plugins/html_output.py @@ -91,17 +91,20 @@ class HTMLOutput(OutputFormatPlugin): # read template files if opts.template_html_index is not None: - template_html_index_data = open(opts.template_html_index, 'rb').read() + with open(opts.template_html_index, 'rb') as f: + template_html_index_data = f.read() else: template_html_index_data = P('templates/html_export_default_index.tmpl', data=True) if opts.template_html is not None: - template_html_data = open(opts.template_html, 'rb').read() + with open(opts.template_html, 'rb') as f: + template_html_data = f.read() else: template_html_data = P('templates/html_export_default.tmpl', data=True) if opts.template_css is not None: - template_css_data = open(opts.template_css, 'rb').read() + with open(opts.template_css, 'rb') as f: + template_css_data = f.read() else: template_css_data = P('templates/html_export_default.css', data=True) diff --git a/src/calibre/ebooks/conversion/plugins/snb_input.py b/src/calibre/ebooks/conversion/plugins/snb_input.py index c250466ff8..4513f282ea 100644 --- a/src/calibre/ebooks/conversion/plugins/snb_input.py +++ b/src/calibre/ebooks/conversion/plugins/snb_input.py @@ -96,15 +96,14 @@ class SNBInput(InputFormatPlugin): if data is None: continue snbc = etree.fromstring(data) - outputFile = open(os.path.join(tdir, fname), 'wb') lines = [] for line in snbc.find('.//body'): if line.tag == 'text': lines.append(u'

%s

' % html_encode(line.text)) elif line.tag == 'img': lines.append(u'

' % html_encode(line.text)) - outputFile.write((HTML_TEMPLATE % (chapterName, u'\n'.join(lines))).encode('utf-8', 'replace')) - outputFile.close() + with open(os.path.join(tdir, fname), 'wb') as f: + f.write((HTML_TEMPLATE % (chapterName, u'\n'.join(lines))).encode('utf-8', 'replace')) oeb.toc.add(ch.text, fname) id, href = oeb.manifest.generate(id='html', href=ascii_filename(fname)) diff --git a/src/calibre/ebooks/conversion/plugins/snb_output.py b/src/calibre/ebooks/conversion/plugins/snb_output.py index 5b4917fc7b..4467045fa2 100644 --- a/src/calibre/ebooks/conversion/plugins/snb_output.py +++ b/src/calibre/ebooks/conversion/plugins/snb_output.py @@ -113,9 +113,8 @@ class SNBOutput(OutputFormatPlugin): etree.SubElement(headTree, "cover").text = ProcessFileName(href) else: etree.SubElement(headTree, "cover") - bookInfoFile = open(os.path.join(snbfDir, 'book.snbf'), 'wb') - bookInfoFile.write(etree.tostring(bookInfoTree, pretty_print=True, encoding='utf-8')) - bookInfoFile.close() + with open(os.path.join(snbfDir, 'book.snbf'), 'wb') as f: + f.write(etree.tostring(bookInfoTree, pretty_print=True, encoding='utf-8')) # Output TOC tocInfoTree = etree.Element("toc-snbf") @@ -168,9 +167,8 @@ class SNBOutput(OutputFormatPlugin): etree.SubElement(tocHead, "chapters").text = '%d' % len(tocBody) - tocInfoFile = open(os.path.join(snbfDir, 'toc.snbf'), 'wb') - tocInfoFile.write(etree.tostring(tocInfoTree, pretty_print=True, encoding='utf-8')) - tocInfoFile.close() + with open(os.path.join(snbfDir, 'toc.snbf'), 'wb') as f: + f.write(etree.tostring(tocInfoTree, pretty_print=True, encoding='utf-8')) # Output Files oldTree = None @@ -185,9 +183,8 @@ class SNBOutput(OutputFormatPlugin): else: if oldTree is not None and mergeLast: log.debug('Output the modified chapter again: %s' % lastName) - outputFile = open(os.path.join(snbcDir, lastName), 'wb') - outputFile.write(etree.tostring(oldTree, pretty_print=True, encoding='utf-8')) - outputFile.close() + with open(os.path.join(snbcDir, lastName), 'wb') as f: + f.write(etree.tostring(oldTree, pretty_print=True, encoding='utf-8')) mergeLast = False log.debug('Converting %s to snbc...' % item.href) @@ -201,9 +198,8 @@ class SNBOutput(OutputFormatPlugin): postfix = '_' + subName lastName = ProcessFileName(item.href + postfix + ".snbc") oldTree = snbcTrees[subName] - outputFile = open(os.path.join(snbcDir, lastName), 'wb') - outputFile.write(etree.tostring(oldTree, pretty_print=True, encoding='utf-8')) - outputFile.close() + with open(os.path.join(snbcDir, lastName), 'wb') as f: + f.write(etree.tostring(oldTree, pretty_print=True, encoding='utf-8')) else: log.debug('Merge %s with last TOC item...' % item.href) snbwriter.merge_content(oldTree, oeb_book, item, [('', _("Start"))], opts) @@ -211,9 +207,8 @@ class SNBOutput(OutputFormatPlugin): # Output the last one if needed log.debug('Output the last modified chapter again: %s' % lastName) if oldTree is not None and mergeLast: - outputFile = open(os.path.join(snbcDir, lastName), 'wb') - outputFile.write(etree.tostring(oldTree, pretty_print=True, encoding='utf-8')) - outputFile.close() + with open(os.path.join(snbcDir, lastName), 'wb') as f: + f.write(etree.tostring(oldTree, pretty_print=True, encoding='utf-8')) mergeLast = False for item in m: diff --git a/src/calibre/ebooks/lrf/lrfparser.py b/src/calibre/ebooks/lrf/lrfparser.py index 102c4ad2d5..cfb85eeae4 100644 --- a/src/calibre/ebooks/lrf/lrfparser.py +++ b/src/calibre/ebooks/lrf/lrfparser.py @@ -79,7 +79,8 @@ class LRFDocument(LRFMetaFile): def write_files(self): for obj in chain(itervalues(self.image_map), itervalues(self.font_map)): - open(obj.file, 'wb').write(obj.stream) + with open(obj.file, 'wb') as f: + f.write(obj.stream) def to_xml(self, write_files=True): bookinfo = u'\n\n\n' @@ -96,7 +97,8 @@ class LRFDocument(LRFMetaFile): prefix = ascii_filename(self.metadata.title) bookinfo += u'\n'%(prefix+'_thumbnail.'+self.doc_info.thumbnail_extension,) if write_files: - open(prefix+'_thumbnail.'+self.doc_info.thumbnail_extension, 'wb').write(th) + with open(prefix+'_thumbnail.'+self.doc_info.thumbnail_extension, 'wb') as f: + f.write(th) bookinfo += u'%s\n'%(self.doc_info.language,) bookinfo += u'%s\n'%(self.doc_info.creator,) bookinfo += u'%s\n'%(self.doc_info.producer,) @@ -159,13 +161,13 @@ def main(args=sys.argv, logger=None): return 1 if opts.out is None: opts.out = os.path.join(os.path.dirname(args[1]), os.path.splitext(os.path.basename(args[1]))[0]+".lrs") - o = codecs.open(os.path.abspath(os.path.expanduser(opts.out)), 'wb', 'utf-8') - o.write(u'\n') logger.info(_('Parsing LRF...')) d = LRFDocument(open(args[1], 'rb')) d.parse() logger.info(_('Creating XML...')) - o.write(d.to_xml(write_files=opts.output_resources)) + with codecs.open(os.path.abspath(os.path.expanduser(opts.out)), 'wb', 'utf-8') as f: + f.write('\n') + f.write(d.to_xml(write_files=opts.output_resources)) logger.info(_('LRS written to ')+opts.out) return 0 diff --git a/src/calibre/ebooks/lrf/meta.py b/src/calibre/ebooks/lrf/meta.py index c0a16e5efa..20a5435f32 100644 --- a/src/calibre/ebooks/lrf/meta.py +++ b/src/calibre/ebooks/lrf/meta.py @@ -703,9 +703,8 @@ def main(args=sys.argv): lrf.producer = options.producer if options.thumbnail: path = os.path.expanduser(os.path.expandvars(options.thumbnail)) - f = open(path, "rb") - lrf.thumbnail = f.read() - f.close() + with open(path, "rb") as f: + lrf.thumbnail = f.read() if options.book_id is not None: lrf.book_id = options.book_id if options.comment: @@ -716,9 +715,8 @@ def main(args=sys.argv): td = "None" if t and len(t) > 0: td = os.path.basename(args[1])+"_thumbnail."+lrf.thumbail_extension() - f = open(td, "w") - f.write(t) - f.close() + with open(td, "w") as f: + f.write(t) fields = LRFMetaFile.__dict__.items() fields.sort() @@ -734,7 +732,8 @@ def main(args=sys.argv): ext, data = None, None if data: cover = os.path.splitext(os.path.basename(args[1]))[0]+"_cover."+ext - open(cover, 'wb').write(data) + with open(cover, 'wb') as f: + f.write(data) print('Cover:', cover) else: print('Could not find cover in the LRF file')