diff --git a/recipes/go_comics.recipe b/recipes/go_comics.recipe
index 26217ac8f1..740e4317c9 100644
--- a/recipes/go_comics.recipe
+++ b/recipes/go_comics.recipe
@@ -573,7 +573,7 @@ class GoComics(BasicNewsRecipe):
fname = ascii_filename('%03d_%s' % (num, title)).replace(' ', '_')
path = os.path.join(self.gocomics_dir, fname)
html = '
{h1}{date}
{img}
'.format(**data)
- with lopen(path, 'wb') as f:
+ with open(path, 'wb') as f:
f.write(html.encode('utf-8'))
return {'title':'Page %d of %s' % ((num + 1), title), 'url': ('file:' if iswindows else 'file://') + path.replace(os.sep, '/')}
diff --git a/src/calibre/db/adding.py b/src/calibre/db/adding.py
index 372b19e936..58452b32a0 100644
--- a/src/calibre/db/adding.py
+++ b/src/calibre/db/adding.py
@@ -244,7 +244,7 @@ def add_catalog(cache, path, title, dbapi=None):
fmt = os.path.splitext(path)[1][1:].lower()
new_book_added = False
- with lopen(path, 'rb') as stream:
+ with open(path, 'rb') as stream:
with cache.write_lock:
matches = cache._search('title:="{}" and tags:="{}"'.format(title.replace('"', '\\"'), _('Catalog')), None)
db_id = None
@@ -276,7 +276,7 @@ def add_news(cache, path, arg, dbapi=None):
from calibre.utils.date import utcnow
fmt = os.path.splitext(getattr(path, 'name', path))[1][1:].lower()
- stream = path if hasattr(path, 'read') else lopen(path, 'rb')
+ stream = path if hasattr(path, 'read') else open(path, 'rb')
stream.seek(0)
mi = get_metadata(stream, fmt, use_libprs_metadata=False,
force_read_metadata=True)
diff --git a/src/calibre/db/backend.py b/src/calibre/db/backend.py
index 0cd4a35db3..19b941dd1d 100644
--- a/src/calibre/db/backend.py
+++ b/src/calibre/db/backend.py
@@ -1273,7 +1273,7 @@ class DB:
shell = Shell(db=self.conn, stdout=buf)
shell.process_command('.dump')
else:
- with lopen(fname, 'wb') as buf:
+ with open(fname, 'wb') as buf:
buf.write(sql if isinstance(sql, bytes) else sql.encode('utf-8'))
with TemporaryFile(suffix='_tmpdb.db', dir=os.path.dirname(self.dbpath)) as tmpdb:
@@ -1467,7 +1467,7 @@ class DB:
path = self.format_abspath(book_id, fmt, fname, path)
if path is None:
return missing_value
- with lopen(path, 'r+b') as f:
+ with open(path, 'r+b') as f:
return func(f)
def format_hash(self, book_id, fmt, fname, path):
@@ -1475,7 +1475,7 @@ class DB:
if path is None:
raise NoSuchFormat('Record %d has no fmt: %s'%(book_id, fmt))
sha = hashlib.sha256()
- with lopen(path, 'rb') as f:
+ with open(path, 'rb') as f:
while True:
raw = f.read(SPOOL_SIZE)
sha.update(raw)
@@ -1538,11 +1538,11 @@ class DB:
else:
if os.access(path, os.R_OK):
try:
- f = lopen(path, 'rb')
+ f = open(path, 'rb')
except OSError:
time.sleep(0.2)
try:
- f = lopen(path, 'rb')
+ f = open(path, 'rb')
except OSError as e:
# Ensure the path that caused this error is reported
raise Exception(f'Failed to open {path!r} with error: {e}')
@@ -1564,7 +1564,7 @@ class DB:
return True
except:
pass
- with lopen(dest, 'wb') as d:
+ with open(dest, 'wb') as d:
shutil.copyfileobj(f, d)
return True
return False
@@ -1578,10 +1578,10 @@ class DB:
if abs(timestamp - stat.st_mtime) < 0.1:
return True, None, None
try:
- f = lopen(path, 'rb')
+ f = open(path, 'rb')
except OSError:
time.sleep(0.2)
- f = lopen(path, 'rb')
+ f = open(path, 'rb')
with f:
return True, f.read(), stat.st_mtime
@@ -1620,7 +1620,7 @@ class DB:
os.remove(path)
else:
if no_processing:
- with lopen(path, 'wb') as f:
+ with open(path, 'wb') as f:
f.write(data)
else:
from calibre.utils.img import save_cover_data_to
@@ -1651,7 +1651,7 @@ class DB:
windows_atomic_move.copy_path_to(path, dest)
else:
if hasattr(dest, 'write'):
- with lopen(path, 'rb') as f:
+ with open(path, 'rb') as f:
if report_file_size is not None:
f.seek(0, os.SEEK_END)
report_file_size(f.tell())
@@ -1674,7 +1674,7 @@ class DB:
return True
except:
pass
- with lopen(path, 'rb') as f, lopen(dest, 'wb') as d:
+ with open(path, 'rb') as f, open(dest, 'wb') as d:
shutil.copyfileobj(f, d)
return True
@@ -1720,7 +1720,7 @@ class DB:
traceback.print_exc()
if (not getattr(stream, 'name', False) or not samefile(dest, stream.name)):
- with lopen(dest, 'wb') as f:
+ with open(dest, 'wb') as f:
shutil.copyfileobj(stream, f)
size = f.tell()
if mtime is not None:
@@ -1822,7 +1822,7 @@ class DB:
def write_backup(self, path, raw):
path = os.path.abspath(os.path.join(self.library_path, path, 'metadata.opf'))
try:
- with lopen(path, 'wb') as f:
+ with open(path, 'wb') as f:
f.write(raw)
except OSError:
exc_info = sys.exc_info()
@@ -1835,12 +1835,12 @@ class DB:
raise
finally:
del exc_info
- with lopen(path, 'wb') as f:
+ with open(path, 'wb') as f:
f.write(raw)
def read_backup(self, path):
path = os.path.abspath(os.path.join(self.library_path, path, 'metadata.opf'))
- with lopen(path, 'rb') as f:
+ with open(path, 'rb') as f:
return f.read()
def remove_books(self, path_map, permanent=False):
diff --git a/src/calibre/db/cache.py b/src/calibre/db/cache.py
index dd9c0bebbb..c7508026bc 100644
--- a/src/calibre/db/cache.py
+++ b/src/calibre/db/cache.py
@@ -1687,7 +1687,7 @@ class Cache:
try:
cdata = mi.cover_data[1]
if cdata is None and isinstance(mi.cover, string_or_bytes) and mi.cover and os.access(mi.cover, os.R_OK):
- with lopen(mi.cover, 'rb') as f:
+ with open(mi.cover, 'rb') as f:
cdata = f.read() or None
if cdata is not None:
self._set_cover({book_id: cdata})
@@ -1787,7 +1787,7 @@ class Cache:
# message in the GUI during the processing.
npath = run_import_plugins(stream_or_path, fmt)
fmt = os.path.splitext(npath)[-1].lower().replace('.', '').upper()
- stream_or_path = lopen(npath, 'rb')
+ stream_or_path = open(npath, 'rb')
needs_close = True
fmt = check_ebook_format(stream_or_path, fmt)
@@ -1807,10 +1807,10 @@ class Cache:
if hasattr(stream_or_path, 'read'):
stream = stream_or_path
else:
- stream = lopen(stream_or_path, 'rb')
+ stream = open(stream_or_path, 'rb')
needs_close = True
try:
- stream = stream_or_path if hasattr(stream_or_path, 'read') else lopen(stream_or_path, 'rb')
+ stream = stream_or_path if hasattr(stream_or_path, 'read') else open(stream_or_path, 'rb')
size, fname = self._do_add_format(book_id, fmt, stream, name)
finally:
if needs_close:
@@ -2711,7 +2711,7 @@ class Cache:
pt.close()
self.backend.backup_database(pt.name)
dbkey = key_prefix + ':::' + 'metadata.db'
- with lopen(pt.name, 'rb') as f:
+ with open(pt.name, 'rb') as f:
exporter.add_file(f, dbkey)
os.remove(pt.name)
poff = 1
@@ -2723,7 +2723,7 @@ class Cache:
pt.close()
self.backend.backup_fts_database(pt.name)
ftsdbkey = key_prefix + ':::' + 'full-text-search.db'
- with lopen(pt.name, 'rb') as f:
+ with open(pt.name, 'rb') as f:
exporter.add_file(f, ftsdbkey)
os.remove(pt.name)
diff --git a/src/calibre/db/cli/cmd_add.py b/src/calibre/db/cli/cmd_add.py
index 414fdae4b4..90d4c132ff 100644
--- a/src/calibre/db/cli/cmd_add.py
+++ b/src/calibre/db/cli/cmd_add.py
@@ -113,7 +113,7 @@ def book(db, notify_changes, is_remote, args):
data, fname, fmt, add_duplicates, otitle, oauthors, oisbn, otags, oseries, oseries_index, ocover, oidentifiers, olanguages, oautomerge, request_id = args
with add_ctx(), TemporaryDirectory('add-single') as tdir, run_import_plugins_before_metadata(tdir):
if is_remote:
- with lopen(os.path.join(tdir, fname), 'wb') as f:
+ with open(os.path.join(tdir, fname), 'wb') as f:
f.write(data[1])
path = f.name
else:
@@ -121,7 +121,7 @@ def book(db, notify_changes, is_remote, args):
path = run_import_plugins([path])[0]
fmt = os.path.splitext(path)[1]
fmt = (fmt[1:] if fmt else None) or 'unknown'
- with lopen(path, 'rb') as stream:
+ with open(path, 'rb') as stream:
mi = get_metadata(stream, stream_type=fmt, use_libprs_metadata=True)
if not mi.title:
mi.title = os.path.splitext(os.path.basename(path))[0]
@@ -157,7 +157,7 @@ def format_group(db, notify_changes, is_remote, args):
if is_remote:
paths = []
for name, data in formats:
- with lopen(os.path.join(tdir, os.path.basename(name)), 'wb') as f:
+ with open(os.path.join(tdir, os.path.basename(name)), 'wb') as f:
f.write(data)
paths.append(f.name)
else:
@@ -254,13 +254,13 @@ def do_add(
cover_data = None
for fmt in formats:
if fmt.lower().endswith('.opf'):
- with lopen(fmt, 'rb') as f:
+ with open(fmt, 'rb') as f:
mi = get_metadata(f, stream_type='opf')
if mi.cover_data and mi.cover_data[1]:
cover_data = mi.cover_data[1]
elif mi.cover:
try:
- with lopen(mi.cover, 'rb') as f:
+ with open(mi.cover, 'rb') as f:
cover_data = f.read()
except OSError:
pass
diff --git a/src/calibre/db/cli/cmd_export.py b/src/calibre/db/cli/cmd_export.py
index 022892ffdb..38eeaf8f94 100644
--- a/src/calibre/db/cli/cmd_export.py
+++ b/src/calibre/db/cli/cmd_export.py
@@ -115,7 +115,7 @@ class DBProxy:
if self.dbctx.is_remote:
if fdata is None:
raise NoSuchFormat(fmt)
- with lopen(path, 'wb') as f:
+ with open(path, 'wb') as f:
f.write(fdata)
diff --git a/src/calibre/db/cli/cmd_list.py b/src/calibre/db/cli/cmd_list.py
index ad2c934249..9907b26001 100644
--- a/src/calibre/db/cli/cmd_list.py
+++ b/src/calibre/db/cli/cmd_list.py
@@ -166,7 +166,7 @@ def do_list(
ascending = True
if 'template' in (f.strip() for f in fields):
if template_file:
- with lopen(template_file, 'rb') as f:
+ with open(template_file, 'rb') as f:
template = f.read().decode('utf-8')
if not template:
raise SystemExit(_('You must provide a template'))
diff --git a/src/calibre/db/cli/cmd_restore_database.py b/src/calibre/db/cli/cmd_restore_database.py
index 2ac1e2296a..3488d6585d 100644
--- a/src/calibre/db/cli/cmd_restore_database.py
+++ b/src/calibre/db/cli/cmd_restore_database.py
@@ -76,7 +76,7 @@ def main(opts, args, dbctx):
prints('old database saved as', r.olddb)
if r.errors_occurred:
name = 'calibre_db_restore_report.txt'
- lopen('calibre_db_restore_report.txt',
+ open('calibre_db_restore_report.txt',
'wb').write(r.report.encode('utf-8'))
prints('Some errors occurred. A detailed report was ' 'saved to', name)
diff --git a/src/calibre/db/cli/cmd_set_metadata.py b/src/calibre/db/cli/cmd_set_metadata.py
index e672471203..3e4b2e8d7d 100644
--- a/src/calibre/db/cli/cmd_set_metadata.py
+++ b/src/calibre/db/cli/cmd_set_metadata.py
@@ -143,7 +143,7 @@ def main(opts, args, dbctx):
opf = os.path.abspath(args[1])
if not os.path.exists(opf):
raise SystemExit(_('The OPF file %s does not exist') % opf)
- with lopen(opf, 'rb') as stream:
+ with open(opf, 'rb') as stream:
mi = get_metadata(stream)[0]
if mi.cover:
mi.cover = os.path.join(os.path.dirname(opf), os.path.relpath(mi.cover, os.getcwd()))
diff --git a/src/calibre/db/cli/main.py b/src/calibre/db/cli/main.py
index 01e52e20b5..0aaaeecb0a 100644
--- a/src/calibre/db/cli/main.py
+++ b/src/calibre/db/cli/main.py
@@ -119,7 +119,7 @@ def read_credentials(opts):
from getpass import getpass
pw = getpass(_('Enter the password: '))
elif pw.startswith(''):
- with lopen(pw[3:-1], 'rb') as f:
+ with open(pw[3:-1], 'rb') as f:
pw = f.read().decode('utf-8').rstrip()
return username, pw
@@ -173,7 +173,7 @@ class DBCtx:
def path(self, path):
if self.is_remote:
- with lopen(path, 'rb') as f:
+ with open(path, 'rb') as f:
return path, f.read()
return path
diff --git a/src/calibre/db/utils.py b/src/calibre/db/utils.py
index 04dbc96ea5..2d3fc1deae 100644
--- a/src/calibre/db/utils.py
+++ b/src/calibre/db/utils.py
@@ -227,7 +227,7 @@ class ThumbnailCache:
if hasattr(self, 'items'):
try:
data = '\n'.join(group_id + ' ' + str(book_id) for (group_id, book_id) in self.items)
- with lopen(os.path.join(self.location, 'order'), 'wb') as f:
+ with open(os.path.join(self.location, 'order'), 'wb') as f:
f.write(data.encode('utf-8'))
except OSError as err:
self.log('Failed to save thumbnail cache order:', as_unicode(err))
@@ -235,7 +235,7 @@ class ThumbnailCache:
def _read_order(self):
order = {}
try:
- with lopen(os.path.join(self.location, 'order'), 'rb') as f:
+ with open(os.path.join(self.location, 'order'), 'rb') as f:
for line in f.read().decode('utf-8').splitlines():
parts = line.split(' ', 1)
if len(parts) == 2:
diff --git a/src/calibre/devices/__init__.py b/src/calibre/devices/__init__.py
index bf5db6eb5a..d1427d1ad7 100644
--- a/src/calibre/devices/__init__.py
+++ b/src/calibre/devices/__init__.py
@@ -184,7 +184,7 @@ def debug(ioreg_to_tmp=False, buf=None, plugins=None,
ioreg = 'IOREG Output\n'+ioreg
out(' ')
if ioreg_to_tmp:
- lopen('/tmp/ioreg.txt', 'w').write(ioreg)
+ open('/tmp/ioreg.txt', 'w').write(ioreg)
out('Dont forget to send the contents of /tmp/ioreg.txt')
out('You can open it with the command: open /tmp/ioreg.txt')
else:
diff --git a/src/calibre/devices/android/driver.py b/src/calibre/devices/android/driver.py
index facd064009..1f965f2581 100644
--- a/src/calibre/devices/android/driver.py
+++ b/src/calibre/devices/android/driver.py
@@ -385,7 +385,7 @@ class WEBOS(USBMS):
if coverdata and coverdata[2]:
cover = Image.open(io.BytesIO(coverdata[2]))
else:
- coverdata = lopen(I('library.png'), 'rb').read()
+ coverdata = open(I('library.png'), 'rb').read()
cover = Image.new('RGB', (120,160), 'black')
im = Image.open(io.BytesIO(coverdata))
@@ -402,7 +402,7 @@ class WEBOS(USBMS):
cover.save(data, 'JPEG')
coverdata = data.getvalue()
- with lopen(os.path.join(path, 'coverCache', filename + '-medium.jpg'), 'wb') as coverfile:
+ with open(os.path.join(path, 'coverCache', filename + '-medium.jpg'), 'wb') as coverfile:
coverfile.write(coverdata)
fsync(coverfile)
@@ -410,7 +410,7 @@ class WEBOS(USBMS):
if coverdata and coverdata[2]:
cover = Image.open(io.BytesIO(coverdata[2]))
else:
- coverdata = lopen(I('library.png'), 'rb').read()
+ coverdata = open(I('library.png'), 'rb').read()
cover = Image.new('RGB', (52,69), 'black')
im = Image.open(io.BytesIO(coverdata))
@@ -425,6 +425,6 @@ class WEBOS(USBMS):
cover2.save(data, 'JPEG')
coverdata = data.getvalue()
- with lopen(os.path.join(path, 'coverCache', filename + '-small.jpg'), 'wb') as coverfile:
+ with open(os.path.join(path, 'coverCache', filename + '-small.jpg'), 'wb') as coverfile:
coverfile.write(coverdata)
fsync(coverfile)
diff --git a/src/calibre/devices/cli.py b/src/calibre/devices/cli.py
index 1497f81ae4..1fb276d728 100755
--- a/src/calibre/devices/cli.py
+++ b/src/calibre/devices/cli.py
@@ -300,7 +300,7 @@ def main():
if os.path.isdir(outfile):
outfile = os.path.join(outfile, path[path.rfind("/")+1:])
try:
- outfile = lopen(outfile, "wb")
+ outfile = open(outfile, "wb")
except OSError as e:
print(e, file=sys.stderr)
parser.print_help()
@@ -310,7 +310,7 @@ def main():
outfile.close()
elif args[1].startswith("dev:"):
try:
- infile = lopen(args[0], "rb")
+ infile = open(args[0], "rb")
except OSError as e:
print(e, file=sys.stderr)
parser.print_help()
@@ -361,7 +361,7 @@ def main():
return 1
path = args[0]
from calibre.ebooks.metadata.meta import get_metadata
- mi = get_metadata(lopen(path, 'rb'), path.rpartition('.')[-1].lower())
+ mi = get_metadata(open(path, 'rb'), path.rpartition('.')[-1].lower())
print(dev.upload_books([args[0]], [os.path.basename(args[0])],
end_session=False, metadata=[mi]))
dev.eject()
diff --git a/src/calibre/devices/cybook/driver.py b/src/calibre/devices/cybook/driver.py
index adf991af72..c0e12261d2 100644
--- a/src/calibre/devices/cybook/driver.py
+++ b/src/calibre/devices/cybook/driver.py
@@ -49,7 +49,7 @@ class CYBOOK(USBMS):
coverdata = coverdata[2]
else:
coverdata = None
- with lopen('%s_6090.t2b' % os.path.join(path, filename), 'wb') as t2bfile:
+ with open('%s_6090.t2b' % os.path.join(path, filename), 'wb') as t2bfile:
t2b.write_t2b(t2bfile, coverdata)
fsync(t2bfile)
@@ -89,7 +89,7 @@ class ORIZON(CYBOOK):
coverdata = coverdata[2]
else:
coverdata = None
- with lopen('%s.thn' % filepath, 'wb') as thnfile:
+ with open('%s.thn' % filepath, 'wb') as thnfile:
t4b.write_t4b(thnfile, coverdata)
fsync(thnfile)
diff --git a/src/calibre/devices/hanvon/driver.py b/src/calibre/devices/hanvon/driver.py
index 3c9e2b3ba7..acb2977b05 100644
--- a/src/calibre/devices/hanvon/driver.py
+++ b/src/calibre/devices/hanvon/driver.py
@@ -126,7 +126,7 @@ class ALEX(N516):
cdir = os.path.dirname(cpath)
if not os.path.exists(cdir):
os.makedirs(cdir)
- with lopen(cpath, 'wb') as coverfile:
+ with open(cpath, 'wb') as coverfile:
coverfile.write(cover)
fsync(coverfile)
diff --git a/src/calibre/devices/kindle/apnx.py b/src/calibre/devices/kindle/apnx.py
index e2c5856d25..2f80656f34 100644
--- a/src/calibre/devices/kindle/apnx.py
+++ b/src/calibre/devices/kindle/apnx.py
@@ -57,7 +57,7 @@ class APNXBuilder:
apnx = self.generate_apnx(pages, apnx_meta)
# Write the APNX.
- with lopen(apnx_path, 'wb') as apnxf:
+ with open(apnx_path, 'wb') as apnxf:
apnxf.write(apnx)
fsync(apnxf)
@@ -71,14 +71,14 @@ class APNXBuilder:
'format': 'MOBI_7',
'acr': ''
}
- with lopen(mobi_file_path, 'rb') as mf:
+ with open(mobi_file_path, 'rb') as mf:
ident = PdbHeaderReader(mf).identity()
if as_bytes(ident) != b'BOOKMOBI':
# Check that this is really a MOBI file.
raise Exception(_('Not a valid MOBI file. Reports identity of %s') % ident)
apnx_meta['acr'] = as_unicode(PdbHeaderReader(mf).name(), errors='replace')
# We'll need the PDB name, the MOBI version, and some metadata to make FW 3.4 happy with KF8 files...
- with lopen(mobi_file_path, 'rb') as mf:
+ with open(mobi_file_path, 'rb') as mf:
mh = MetadataHeader(mf, default_log)
if mh.mobi_version == 8:
apnx_meta['format'] = 'MOBI_8'
diff --git a/src/calibre/devices/kindle/apnx_page_generator/i_page_generator.py b/src/calibre/devices/kindle/apnx_page_generator/i_page_generator.py
index 62b2265c4b..124a606101 100644
--- a/src/calibre/devices/kindle/apnx_page_generator/i_page_generator.py
+++ b/src/calibre/devices/kindle/apnx_page_generator/i_page_generator.py
@@ -48,7 +48,7 @@ def mobi_html(mobi_file_path: str) -> bytes:
def mobi_html_length(mobi_file_path: str) -> int:
- with lopen(mobi_file_path, 'rb') as mf:
+ with open(mobi_file_path, 'rb') as mf:
pdb_header = PdbHeaderReader(mf)
r0 = pdb_header.section_data(0)
return struct.unpack('>I', r0[4:8])[0]
diff --git a/src/calibre/devices/kindle/bookmark.py b/src/calibre/devices/kindle/bookmark.py
index 1d9b240d1c..6c2196bd53 100644
--- a/src/calibre/devices/kindle/bookmark.py
+++ b/src/calibre/devices/kindle/bookmark.py
@@ -47,7 +47,7 @@ class Bookmark(): # {{{
user_notes = {}
if self.bookmark_extension == 'mbp':
MAGIC_MOBI_CONSTANT = 150
- with lopen(self.path,'rb') as f:
+ with open(self.path,'rb') as f:
stream = io.BytesIO(f.read())
data = StreamSlicer(stream)
self.timestamp, = unpack('>I', data[0x24:0x28])
@@ -144,7 +144,7 @@ class Bookmark(): # {{{
# Author is not matched
# This will find the first instance of a clipping only
book_fs = self.path.replace('.%s' % self.bookmark_extension,'.%s' % self.book_format)
- with lopen(book_fs,'rb') as f2:
+ with open(book_fs,'rb') as f2:
stream = io.BytesIO(f2.read())
mi = get_topaz_metadata(stream)
my_clippings = self.path
@@ -175,7 +175,7 @@ class Bookmark(): # {{{
MAGIC_TOPAZ_CONSTANT = 33.33
self.timestamp = os.path.getmtime(self.path)
- with lopen(self.path,'rb') as f:
+ with open(self.path,'rb') as f:
stream = io.BytesIO(f.read())
data = StreamSlicer(stream)
self.last_read = int(unpack('>I', data[5:9])[0])
@@ -216,7 +216,7 @@ class Bookmark(): # {{{
elif self.bookmark_extension == 'pdr':
self.timestamp = os.path.getmtime(self.path)
- with lopen(self.path,'rb') as f:
+ with open(self.path,'rb') as f:
stream = io.BytesIO(f.read())
data = StreamSlicer(stream)
self.last_read = int(unpack('>I', data[5:9])[0])
@@ -285,7 +285,7 @@ class Bookmark(): # {{{
if self.bookmark_extension == 'mbp':
# Read the book len from the header
try:
- with lopen(book_fs,'rb') as f:
+ with open(book_fs,'rb') as f:
self.stream = io.BytesIO(f.read())
self.data = StreamSlicer(self.stream)
self.nrecs, = unpack('>H', self.data[76:78])
@@ -297,7 +297,7 @@ class Bookmark(): # {{{
# Read bookLength from metadata
from calibre.ebooks.metadata.topaz import MetadataUpdater
try:
- with lopen(book_fs,'rb') as f:
+ with open(book_fs,'rb') as f:
mu = MetadataUpdater(f)
self.book_length = mu.book_length
except:
diff --git a/src/calibre/devices/kindle/driver.py b/src/calibre/devices/kindle/driver.py
index 647498f754..3b72b9b200 100644
--- a/src/calibre/devices/kindle/driver.py
+++ b/src/calibre/devices/kindle/driver.py
@@ -121,13 +121,13 @@ class KINDLE(USBMS):
from calibre.ebooks.metadata.kfx import read_metadata_kfx
try:
kfx_path = path
- with lopen(kfx_path, 'rb') as f:
+ with open(kfx_path, 'rb') as f:
if f.read(8) != b'\xeaDRMION\xee':
f.seek(0)
mi = read_metadata_kfx(f)
else:
kfx_path = os.path.join(path.rpartition('.')[0] + '.sdr', 'assets', 'metadata.kfx')
- with lopen(kfx_path, 'rb') as mf:
+ with open(kfx_path, 'rb') as mf:
mi = read_metadata_kfx(mf)
except Exception:
import traceback
@@ -443,7 +443,7 @@ class KINDLE2(KINDLE):
return bl
def kindle_update_booklist(self, bl, collections):
- with lopen(collections, 'rb') as f:
+ with open(collections, 'rb') as f:
collections = f.read()
collections = json.loads(collections)
path_map = {}
@@ -503,7 +503,7 @@ class KINDLE2(KINDLE):
thumb_dir = self.amazon_system_thumbnails_dir()
if not os.path.exists(thumb_dir):
return
- with lopen(filepath, 'rb') as f:
+ with open(filepath, 'rb') as f:
is_kfx = f.read(4) == CONTAINER_MAGIC
f.seek(0)
uuid = cdetype = None
@@ -531,7 +531,7 @@ class KINDLE2(KINDLE):
tp = self.thumbpath_from_filepath(filepath)
if tp:
- with lopen(tp, 'wb') as f:
+ with open(tp, 'wb') as f:
f.write(coverdata[2])
fsync(f)
cache_dir = self.amazon_cover_bug_cache_dir()
@@ -539,7 +539,7 @@ class KINDLE2(KINDLE):
os.mkdir(cache_dir)
except OSError:
pass
- with lopen(os.path.join(cache_dir, os.path.basename(tp)), 'wb') as f:
+ with open(os.path.join(cache_dir, os.path.basename(tp)), 'wb') as f:
f.write(coverdata[2])
fsync(f)
@@ -566,7 +566,7 @@ class KINDLE2(KINDLE):
count += 1
if DEBUG:
prints('Restoring cover thumbnail:', name)
- with lopen(os.path.join(src_dir, name), 'rb') as src, lopen(dest_path, 'wb') as dest:
+ with open(os.path.join(src_dir, name), 'rb') as src, open(dest_path, 'wb') as dest:
shutil.copyfileobj(src, dest)
fsync(dest)
if DEBUG:
diff --git a/src/calibre/devices/kobo/driver.py b/src/calibre/devices/kobo/driver.py
index 6cf6eb7465..0be7234504 100644
--- a/src/calibre/devices/kobo/driver.py
+++ b/src/calibre/devices/kobo/driver.py
@@ -1084,14 +1084,14 @@ class KOBO(USBMS):
fpath = self.normalize_path(fpath.replace('/', os.sep))
if os.path.exists(fpath):
- with lopen(cover, 'rb') as f:
+ with open(cover, 'rb') as f:
data = f.read()
# Return the data resized and grayscaled if
# required
data = save_cover_data_to(data, grayscale=uploadgrayscale, resize_to=resize, minify_to=resize)
- with lopen(fpath, 'wb') as f:
+ with open(fpath, 'wb') as f:
f.write(data)
fsync(f)
@@ -1111,7 +1111,7 @@ class KOBO(USBMS):
'''
for idx, path in enumerate(paths):
if path.find('kepub') >= 0:
- with closing(lopen(path, 'rb')) as r:
+ with closing(open(path, 'rb')) as r:
tf = PersistentTemporaryFile(suffix='.epub')
shutil.copyfileobj(r, tf)
# tf.write(r.read())
@@ -2842,7 +2842,7 @@ class KOBOTOUCH(KOBO):
debug_print("KoboTouch:_upload_cover - Image folder does not exist. Creating path='%s'" % (image_dir))
os.makedirs(image_dir)
- with lopen(cover, 'rb') as f:
+ with open(cover, 'rb') as f:
cover_data = f.read()
fmt, width, height = identify(cover_data)
@@ -2902,7 +2902,7 @@ class KOBOTOUCH(KOBO):
# through a temporary file...
if png_covers:
tmp_cover = better_mktemp()
- with lopen(tmp_cover, 'wb') as f:
+ with open(tmp_cover, 'wb') as f:
f.write(data)
optimize_png(tmp_cover, level=1)
@@ -2910,7 +2910,7 @@ class KOBOTOUCH(KOBO):
shutil.copy2(tmp_cover, fpath)
os.remove(tmp_cover)
else:
- with lopen(fpath, 'wb') as f:
+ with open(fpath, 'wb') as f:
f.write(data)
fsync(f)
except Exception as e:
diff --git a/src/calibre/devices/misc.py b/src/calibre/devices/misc.py
index 1c35bf4dc7..4cd63e2d1e 100644
--- a/src/calibre/devices/misc.py
+++ b/src/calibre/devices/misc.py
@@ -98,7 +98,7 @@ class PDNOVEL(USBMS):
def upload_cover(self, path, filename, metadata, filepath):
coverdata = getattr(metadata, 'thumbnail', None)
if coverdata and coverdata[2]:
- with lopen('%s.jpg' % os.path.join(path, filename), 'wb') as coverfile:
+ with open('%s.jpg' % os.path.join(path, filename), 'wb') as coverfile:
coverfile.write(coverdata[2])
fsync(coverfile)
@@ -118,7 +118,7 @@ class PDNOVEL_KOBO(PDNOVEL):
dirpath = os.path.join(path, '.thumbnail')
if not os.path.exists(dirpath):
os.makedirs(dirpath)
- with lopen(os.path.join(dirpath, filename+'.jpg'), 'wb') as coverfile:
+ with open(os.path.join(dirpath, filename+'.jpg'), 'wb') as coverfile:
coverfile.write(coverdata[2])
fsync(coverfile)
@@ -193,7 +193,7 @@ class LUMIREAD(USBMS):
pdir = os.path.dirname(cfilepath)
if not os.path.exists(pdir):
os.makedirs(pdir)
- with lopen(cfilepath+'.jpg', 'wb') as f:
+ with open(cfilepath+'.jpg', 'wb') as f:
f.write(metadata.thumbnail[-1])
fsync(f)
@@ -345,7 +345,7 @@ class NEXTBOOK(USBMS):
thumbnail_dir = os.path.join(thumbnail_dir, relpath)
if not os.path.exists(thumbnail_dir):
os.makedirs(thumbnail_dir)
- with lopen(os.path.join(thumbnail_dir, filename+'.jpg'), 'wb') as f:
+ with open(os.path.join(thumbnail_dir, filename+'.jpg'), 'wb') as f:
f.write(metadata.thumbnail[-1])
fsync(f)
'''
diff --git a/src/calibre/devices/mtp/driver.py b/src/calibre/devices/mtp/driver.py
index 7452c5cf86..6d12c601e0 100644
--- a/src/calibre/devices/mtp/driver.py
+++ b/src/calibre/devices/mtp/driver.py
@@ -344,7 +344,7 @@ class MTP_DEVICE(BASE):
if iswindows:
plen = len(base)
name = ''.join(shorten_components_to(245-plen, [name]))
- with lopen(os.path.join(base, name), 'wb') as out:
+ with open(os.path.join(base, name), 'wb') as out:
try:
self.get_mtp_file(f, out)
except Exception as e:
@@ -435,7 +435,7 @@ class MTP_DEVICE(BASE):
close = False
else:
sz = os.path.getsize(infile)
- stream = lopen(infile, 'rb')
+ stream = open(infile, 'rb')
close = True
try:
mtp_file = self.put_file(parent, path[-1], stream, sz)
diff --git a/src/calibre/devices/mtp/unix/sysfs.py b/src/calibre/devices/mtp/unix/sysfs.py
index 0200209d6e..95159069ea 100644
--- a/src/calibre/devices/mtp/unix/sysfs.py
+++ b/src/calibre/devices/mtp/unix/sysfs.py
@@ -28,7 +28,7 @@ class MTPDetect:
def read(x):
try:
- with lopen(x, 'rb') as f:
+ with open(x, 'rb') as f:
return f.read()
except OSError:
pass
@@ -50,5 +50,3 @@ class MTPDetect:
continue
return False
-
-
diff --git a/src/calibre/devices/nook/driver.py b/src/calibre/devices/nook/driver.py
index cdd5bfe9eb..ad43a2a153 100644
--- a/src/calibre/devices/nook/driver.py
+++ b/src/calibre/devices/nook/driver.py
@@ -51,7 +51,7 @@ class NOOK(USBMS):
if coverdata and coverdata[2]:
cover = Image.open(io.BytesIO(coverdata[2]))
else:
- coverdata = lopen(I('library.png'), 'rb').read()
+ coverdata = open(I('library.png'), 'rb').read()
cover = Image.new('RGB', (96, 144), 'black')
im = Image.open(io.BytesIO(coverdata))
@@ -68,7 +68,7 @@ class NOOK(USBMS):
cover.save(data, 'JPEG')
coverdata = data.getvalue()
- with lopen('%s.jpg' % os.path.join(path, filename), 'wb') as coverfile:
+ with open('%s.jpg' % os.path.join(path, filename), 'wb') as coverfile:
coverfile.write(coverdata)
fsync(coverfile)
diff --git a/src/calibre/devices/prs505/driver.py b/src/calibre/devices/prs505/driver.py
index 0bd4d7b015..8ae6ee8922 100644
--- a/src/calibre/devices/prs505/driver.py
+++ b/src/calibre/devices/prs505/driver.py
@@ -134,7 +134,7 @@ class PRS505(USBMS):
except:
time.sleep(5)
os.makedirs(dname, mode=0o777)
- with lopen(cachep, 'wb') as f:
+ with open(cachep, 'wb') as f:
f.write(b'''
@@ -295,6 +295,6 @@ class PRS505(USBMS):
if not os.path.exists(thumbnail_dir):
os.makedirs(thumbnail_dir)
cpath = os.path.join(thumbnail_dir, 'main_thumbnail.jpg')
- with lopen(cpath, 'wb') as f:
+ with open(cpath, 'wb') as f:
f.write(metadata.thumbnail[-1])
debug_print('Cover uploaded to: %r'%cpath)
diff --git a/src/calibre/devices/prs505/sony_cache.py b/src/calibre/devices/prs505/sony_cache.py
index 7fa4f3788f..c40de0dc46 100644
--- a/src/calibre/devices/prs505/sony_cache.py
+++ b/src/calibre/devices/prs505/sony_cache.py
@@ -105,12 +105,12 @@ class XMLCache:
if not os.path.exists(path):
raise DeviceError(('The SONY XML cache %r does not exist. Try'
' disconnecting and reconnecting your reader.')%repr(path))
- with lopen(path, 'rb') as f:
+ with open(path, 'rb') as f:
raw = f.read()
else:
raw = EMPTY_CARD_CACHE
if os.access(path, os.R_OK):
- with lopen(path, 'rb') as f:
+ with open(path, 'rb') as f:
raw = f.read()
self.roots[source_id] = safe_xml_fromstring(
@@ -124,14 +124,14 @@ class XMLCache:
for source_id, path in ext_paths.items():
if not os.path.exists(path):
try:
- with lopen(path, 'wb') as f:
+ with open(path, 'wb') as f:
f.write(EMPTY_EXT_CACHE)
fsync(f)
except:
pass
if os.access(path, os.W_OK):
try:
- with lopen(path, 'rb') as f:
+ with open(path, 'rb') as f:
self.ext_roots[source_id] = safe_xml_fromstring(
xml_to_unicode(f.read(), strip_encoding_pats=True, assume_utf8=True, verbose=DEBUG)[0]
)
@@ -724,7 +724,7 @@ class XMLCache:
xml_declaration=True)
raw = raw.replace(b"",
b'')
- with lopen(path, 'wb') as f:
+ with open(path, 'wb') as f:
f.write(raw)
fsync(f)
@@ -736,7 +736,7 @@ class XMLCache:
continue
raw = raw.replace(b"",
b'')
- with lopen(path, 'wb') as f:
+ with open(path, 'wb') as f:
f.write(raw)
fsync(f)
diff --git a/src/calibre/devices/prst1/driver.py b/src/calibre/devices/prst1/driver.py
index 647023d6fe..0c74864763 100644
--- a/src/calibre/devices/prst1/driver.py
+++ b/src/calibre/devices/prst1/driver.py
@@ -762,7 +762,7 @@ class PRST1(USBMS):
if not os.path.exists(thumbnail_dir_path):
os.makedirs(thumbnail_dir_path)
- with lopen(thumbnail_file_path, 'wb') as f:
+ with open(thumbnail_file_path, 'wb') as f:
f.write(book.thumbnail[-1])
fsync(f)
diff --git a/src/calibre/devices/scanner.py b/src/calibre/devices/scanner.py
index 073448b818..b8f340a893 100644
--- a/src/calibre/devices/scanner.py
+++ b/src/calibre/devices/scanner.py
@@ -107,7 +107,7 @@ class LinuxScanner:
raise RuntimeError('DeviceScanner requires the /sys filesystem to work.')
def read(f):
- with lopen(f, 'rb') as s:
+ with open(f, 'rb') as s:
return s.read().strip()
for x in os.listdir(self.base):
diff --git a/src/calibre/devices/smart_device_app/driver.py b/src/calibre/devices/smart_device_app/driver.py
index 91fba1a388..26ff658aa8 100644
--- a/src/calibre/devices/smart_device_app/driver.py
+++ b/src/calibre/devices/smart_device_app/driver.py
@@ -703,7 +703,7 @@ class SMART_DEVICE_APP(DeviceConfig, DevicePlugin):
def _put_file(self, infile, lpath, book_metadata, this_book, total_books):
close_ = False
if not hasattr(infile, 'read'):
- infile, close_ = lopen(infile, 'rb'), True
+ infile, close_ = open(infile, 'rb'), True
infile.seek(0, os.SEEK_END)
length = infile.tell()
book_metadata.size = length
@@ -816,7 +816,7 @@ class SMART_DEVICE_APP(DeviceConfig, DevicePlugin):
try:
count = 0
if os.path.exists(cache_file_name):
- with lopen(cache_file_name, mode='rb') as fd:
+ with open(cache_file_name, mode='rb') as fd:
while True:
rec_len = fd.readline()
if len(rec_len) != 8:
@@ -853,7 +853,7 @@ class SMART_DEVICE_APP(DeviceConfig, DevicePlugin):
count = 0
prefix = os.path.join(cache_dir(),
'wireless_device_' + self.device_uuid + '_metadata_cache')
- with lopen(prefix + '.tmp', mode='wb') as fd:
+ with open(prefix + '.tmp', mode='wb') as fd:
for key,book in iteritems(self.device_book_cache):
if (now_ - book['last_used']).days > self.PURGE_CACHE_ENTRIES_DAYS:
purged += 1
@@ -956,7 +956,7 @@ class SMART_DEVICE_APP(DeviceConfig, DevicePlugin):
from calibre.customize.ui import quick_metadata
from calibre.ebooks.metadata.meta import get_metadata
ext = temp_file_name.rpartition('.')[-1].lower()
- with lopen(temp_file_name, 'rb') as stream:
+ with open(temp_file_name, 'rb') as stream:
with quick_metadata:
return get_metadata(stream, stream_type=ext,
force_read_metadata=True,
diff --git a/src/calibre/devices/usbms/cli.py b/src/calibre/devices/usbms/cli.py
index 364ad80c9b..6ad4ce6592 100644
--- a/src/calibre/devices/usbms/cli.py
+++ b/src/calibre/devices/usbms/cli.py
@@ -34,14 +34,14 @@ class CLI:
def get_file(self, path, outfile, end_session=True):
path = self.munge_path(path)
- with lopen(path, 'rb') as src:
+ with open(path, 'rb') as src:
shutil.copyfileobj(src, outfile)
def put_file(self, infile, path, replace_file=False, end_session=True):
path = self.munge_path(path)
close = False
if not hasattr(infile, 'read'):
- infile, close = lopen(infile, 'rb'), True
+ infile, close = open(infile, 'rb'), True
infile.seek(0)
if os.path.isdir(path):
path = os.path.join(path, infile.name)
@@ -99,6 +99,6 @@ class CLI:
def touch(self, path, end_session=True):
path = self.munge_path(path)
if not os.path.exists(path):
- lopen(path, 'wb').close()
+ open(path, 'wb').close()
if not os.path.isdir(path):
os.utime(path, None)
diff --git a/src/calibre/devices/usbms/device.py b/src/calibre/devices/usbms/device.py
index a7b26b36cc..3285cb5195 100644
--- a/src/calibre/devices/usbms/device.py
+++ b/src/calibre/devices/usbms/device.py
@@ -615,7 +615,7 @@ class Device(DeviceConfig, DevicePlugin):
path = os.path.join(mp, 'calibre_readonly_test')
ro = True
try:
- with lopen(path, 'wb'):
+ with open(path, 'wb'):
ro = False
except:
pass
diff --git a/src/calibre/devices/usbms/driver.py b/src/calibre/devices/usbms/driver.py
index d281439f8d..0fc1e9ebd7 100644
--- a/src/calibre/devices/usbms/driver.py
+++ b/src/calibre/devices/usbms/driver.py
@@ -118,7 +118,7 @@ class USBMS(CLI, Device):
def _update_driveinfo_file(self, prefix, location_code, name=None):
from calibre.utils.config import from_json, to_json
if os.path.exists(os.path.join(prefix, self.DRIVEINFO)):
- with lopen(os.path.join(prefix, self.DRIVEINFO), 'rb') as f:
+ with open(os.path.join(prefix, self.DRIVEINFO), 'rb') as f:
try:
driveinfo = json.loads(f.read(), object_hook=from_json)
except:
@@ -128,7 +128,7 @@ class USBMS(CLI, Device):
data = json.dumps(driveinfo, default=to_json)
if not isinstance(data, bytes):
data = data.encode('utf-8')
- with lopen(os.path.join(prefix, self.DRIVEINFO), 'wb') as f:
+ with open(os.path.join(prefix, self.DRIVEINFO), 'wb') as f:
f.write(data)
fsync(f)
else:
@@ -136,7 +136,7 @@ class USBMS(CLI, Device):
data = json.dumps(driveinfo, default=to_json)
if not isinstance(data, bytes):
data = data.encode('utf-8')
- with lopen(os.path.join(prefix, self.DRIVEINFO), 'wb') as f:
+ with open(os.path.join(prefix, self.DRIVEINFO), 'wb') as f:
f.write(data)
fsync(f)
return driveinfo
@@ -460,7 +460,7 @@ class USBMS(CLI, Device):
isinstance(booklists[listid], self.booklist_class)):
if not os.path.exists(prefix):
os.makedirs(self.normalize_path(prefix))
- with lopen(self.normalize_path(os.path.join(prefix, self.METADATA_CACHE)), 'wb') as f:
+ with open(self.normalize_path(os.path.join(prefix, self.METADATA_CACHE)), 'wb') as f:
json_codec.encode_to_file(f, booklists[listid])
fsync(f)
write_prefix(self._main_prefix, 0)
@@ -506,7 +506,7 @@ class USBMS(CLI, Device):
cache_file = cls.normalize_path(os.path.join(prefix, name))
if os.access(cache_file, os.R_OK):
try:
- with lopen(cache_file, 'rb') as f:
+ with open(cache_file, 'rb') as f:
json_codec.decode_from_file(f, bl, cls.book_class, prefix)
except:
import traceback
diff --git a/src/calibre/ebooks/chm/reader.py b/src/calibre/ebooks/chm/reader.py
index 2feb362a5a..102f439857 100644
--- a/src/calibre/ebooks/chm/reader.py
+++ b/src/calibre/ebooks/chm/reader.py
@@ -189,7 +189,7 @@ class CHMReader(CHMFile):
import shutil
shutil.copytree(output_dir, os.path.join(debug_dump, 'debug_dump'))
for lpath in html_files:
- with lopen(lpath, 'r+b') as f:
+ with open(lpath, 'r+b') as f:
data = f.read()
data = self._reformat(data, lpath)
if isinstance(data, str):
diff --git a/src/calibre/ebooks/comic/input.py b/src/calibre/ebooks/comic/input.py
index 5728f6699b..a0424e9f92 100644
--- a/src/calibre/ebooks/comic/input.py
+++ b/src/calibre/ebooks/comic/input.py
@@ -94,11 +94,11 @@ class PageProcessor(list): # {{{
def render(self):
from calibre.utils.img import image_from_data, scale_image, crop_image
- with lopen(self.path_to_page, 'rb') as f:
+ with open(self.path_to_page, 'rb') as f:
img = image_from_data(f.read())
width, height = img.width(), img.height()
if self.num == 0: # First image so create a thumbnail from it
- with lopen(os.path.join(self.dest, 'thumbnail.png'), 'wb') as f:
+ with open(os.path.join(self.dest, 'thumbnail.png'), 'wb') as f:
f.write(scale_image(img, as_png=True)[-1])
self.pages = [img]
if width > height:
@@ -196,7 +196,7 @@ class PageProcessor(list): # {{{
img = quantize_image(img, max_colors=min(256, self.opts.colors))
dest = '%d_%d.%s'%(self.num, i, self.opts.output_format)
dest = os.path.join(self.dest, dest)
- with lopen(dest, 'wb') as f:
+ with open(dest, 'wb') as f:
f.write(image_to_data(img, fmt=self.opts.output_format))
self.append(dest)
# }}}
diff --git a/src/calibre/ebooks/conversion/config.py b/src/calibre/ebooks/conversion/config.py
index 8d0aba9aea..db30f2859b 100644
--- a/src/calibre/ebooks/conversion/config.py
+++ b/src/calibre/ebooks/conversion/config.py
@@ -27,7 +27,7 @@ def save_defaults(name, recs):
os.makedirs(config_dir, exist_ok=True)
- with lopen(path, 'wb'):
+ with open(path, 'wb'):
pass
with ExclusiveFile(path) as f:
f.write(raw)
diff --git a/src/calibre/ebooks/conversion/plugins/chm_input.py b/src/calibre/ebooks/conversion/plugins/chm_input.py
index 058f4b96aa..8a7d8da83c 100644
--- a/src/calibre/ebooks/conversion/plugins/chm_input.py
+++ b/src/calibre/ebooks/conversion/plugins/chm_input.py
@@ -172,7 +172,7 @@ class CHMInput(InputFormatPlugin):
return htmlpath, toc
def _read_file(self, name):
- with lopen(name, 'rb') as f:
+ with open(name, 'rb') as f:
data = f.read()
return data
diff --git a/src/calibre/ebooks/conversion/plugins/epub_input.py b/src/calibre/ebooks/conversion/plugins/epub_input.py
index 6b880cd601..9915c2b169 100644
--- a/src/calibre/ebooks/conversion/plugins/epub_input.py
+++ b/src/calibre/ebooks/conversion/plugins/epub_input.py
@@ -21,7 +21,7 @@ def decrypt_font_data(key, data, algorithm):
def decrypt_font(key, path, algorithm):
- with lopen(path, 'r+b') as f:
+ with open(path, 'r+b') as f:
data = decrypt_font_data(key, f.read(), algorithm)
f.seek(0), f.truncate(), f.write(data)
@@ -220,7 +220,7 @@ class EPUBInput(InputFormatPlugin):
if os.path.exists(guide_cover):
renderer = render_html_svg_workaround(guide_cover, log, root=os.getcwd())
if renderer is not None:
- with lopen('calibre_raster_cover.jpg', 'wb') as f:
+ with open('calibre_raster_cover.jpg', 'wb') as f:
f.write(renderer)
# Set the titlepage guide entry
@@ -235,7 +235,7 @@ class EPUBInput(InputFormatPlugin):
if k.endswith(attr):
return v
try:
- with lopen('META-INF/container.xml', 'rb') as f:
+ with open('META-INF/container.xml', 'rb') as f:
root = safe_xml_fromstring(f.read())
for r in root.xpath('//*[local-name()="rootfile"]'):
if attr(r, 'media-type') != "application/oebps-package+xml":
@@ -342,7 +342,7 @@ class EPUBInput(InputFormatPlugin):
if len(list(opf.iterspine())) == 0:
raise ValueError('No valid entries in the spine of this EPUB')
- with lopen('content.opf', 'wb') as nopf:
+ with open('content.opf', 'wb') as nopf:
nopf.write(opf.render())
return os.path.abspath('content.opf')
@@ -355,7 +355,7 @@ class EPUBInput(InputFormatPlugin):
from calibre.ebooks.oeb.polish.toc import first_child
from calibre.utils.xml_parse import safe_xml_fromstring
from tempfile import NamedTemporaryFile
- with lopen(nav_path, 'rb') as f:
+ with open(nav_path, 'rb') as f:
raw = f.read()
raw = xml_to_unicode(raw, strip_encoding_pats=True, assume_utf8=True)[0]
root = parse(raw, log=log)
@@ -419,7 +419,7 @@ class EPUBInput(InputFormatPlugin):
changed = True
elem.set('data-calibre-removed-titlepage', '1')
if changed:
- with lopen(nav_path, 'wb') as f:
+ with open(nav_path, 'wb') as f:
f.write(serialize(root, 'application/xhtml+xml'))
def postprocess_book(self, oeb, opts, log):
diff --git a/src/calibre/ebooks/conversion/plugins/epub_output.py b/src/calibre/ebooks/conversion/plugins/epub_output.py
index 6b1c55cca4..012eb512b0 100644
--- a/src/calibre/ebooks/conversion/plugins/epub_output.py
+++ b/src/calibre/ebooks/conversion/plugins/epub_output.py
@@ -334,7 +334,7 @@ class EPUBOutput(OutputFormatPlugin):
uris.pop(uri)
continue
self.log.debug('Encrypting font:', uri)
- with lopen(path, 'r+b') as f:
+ with open(path, 'r+b') as f:
data = f.read(1024)
if len(data) >= 1024:
data = bytearray(data)
diff --git a/src/calibre/ebooks/conversion/plugins/fb2_output.py b/src/calibre/ebooks/conversion/plugins/fb2_output.py
index eb9bf110dd..f4e052ba67 100644
--- a/src/calibre/ebooks/conversion/plugins/fb2_output.py
+++ b/src/calibre/ebooks/conversion/plugins/fb2_output.py
@@ -188,7 +188,7 @@ class FB2Output(OutputFormatPlugin):
close = True
if not os.path.exists(os.path.dirname(output_path)) and os.path.dirname(output_path) != '':
os.makedirs(os.path.dirname(output_path))
- out_stream = lopen(output_path, 'wb')
+ out_stream = open(output_path, 'wb')
else:
out_stream = output_path
diff --git a/src/calibre/ebooks/conversion/plugins/htmlz_output.py b/src/calibre/ebooks/conversion/plugins/htmlz_output.py
index 024d1cc135..bb11d1ec6f 100644
--- a/src/calibre/ebooks/conversion/plugins/htmlz_output.py
+++ b/src/calibre/ebooks/conversion/plugins/htmlz_output.py
@@ -112,7 +112,7 @@ class HTMLZOutput(OutputFormatPlugin):
if cover_data:
from calibre.utils.img import save_cover_data_to
cover_path = os.path.join(tdir, 'cover.jpg')
- with lopen(cover_path, 'w') as cf:
+ with open(cover_path, 'w') as cf:
cf.write('')
save_cover_data_to(cover_data, cover_path)
except:
diff --git a/src/calibre/ebooks/conversion/plugins/mobi_input.py b/src/calibre/ebooks/conversion/plugins/mobi_input.py
index 7d515bd015..5af56b6591 100644
--- a/src/calibre/ebooks/conversion/plugins/mobi_input.py
+++ b/src/calibre/ebooks/conversion/plugins/mobi_input.py
@@ -50,14 +50,14 @@ class MOBIInput(InputFormatPlugin):
if raw:
if isinstance(raw, str):
raw = raw.encode('utf-8')
- with lopen('debug-raw.html', 'wb') as f:
+ with open('debug-raw.html', 'wb') as f:
f.write(raw)
from calibre.ebooks.oeb.base import close_self_closing_tags
for f, root in parse_cache.items():
raw = html.tostring(root, encoding='utf-8', method='xml',
include_meta_content_type=False)
raw = close_self_closing_tags(raw)
- with lopen(f, 'wb') as q:
+ with open(f, 'wb') as q:
q.write(raw)
accelerators['pagebreaks'] = '//h:div[@class="mbp_pagebreak"]'
return mr.created_opf_path
diff --git a/src/calibre/ebooks/conversion/plugins/oeb_output.py b/src/calibre/ebooks/conversion/plugins/oeb_output.py
index ed91bfdcfb..2e74faca36 100644
--- a/src/calibre/ebooks/conversion/plugins/oeb_output.py
+++ b/src/calibre/ebooks/conversion/plugins/oeb_output.py
@@ -52,7 +52,7 @@ class OEBOutput(OutputFormatPlugin):
# Needed as I can't get lxml to output opf:role and
# not output as well
raw = re.sub(br'(<[/]{0,1})opf:', br'\1', raw)
- with lopen(href, 'wb') as f:
+ with open(href, 'wb') as f:
f.write(raw)
for item in oeb_book.manifest:
@@ -64,7 +64,7 @@ class OEBOutput(OutputFormatPlugin):
dir = os.path.dirname(path)
if not os.path.exists(dir):
os.makedirs(dir)
- with lopen(path, 'wb') as f:
+ with open(path, 'wb') as f:
f.write(item.bytes_representation)
item.unload_data_from_memory(memory=path)
diff --git a/src/calibre/ebooks/conversion/plugins/pdb_output.py b/src/calibre/ebooks/conversion/plugins/pdb_output.py
index ceb6c8fc60..724092eb18 100644
--- a/src/calibre/ebooks/conversion/plugins/pdb_output.py
+++ b/src/calibre/ebooks/conversion/plugins/pdb_output.py
@@ -38,7 +38,7 @@ class PDBOutput(OutputFormatPlugin):
close = True
if not os.path.exists(os.path.dirname(output_path)) and os.path.dirname(output_path):
os.makedirs(os.path.dirname(output_path))
- out_stream = lopen(output_path, 'wb')
+ out_stream = open(output_path, 'wb')
else:
out_stream = output_path
diff --git a/src/calibre/ebooks/conversion/plugins/pdf_input.py b/src/calibre/ebooks/conversion/plugins/pdf_input.py
index cce1dd21ac..bd934869e8 100644
--- a/src/calibre/ebooks/conversion/plugins/pdf_input.py
+++ b/src/calibre/ebooks/conversion/plugins/pdf_input.py
@@ -33,7 +33,7 @@ class PDFInput(InputFormatPlugin):
from calibre.ebooks.pdf.reflow import PDFDocument
pdftohtml(os.getcwd(), stream.name, self.opts.no_images, as_xml=True)
- with lopen('index.xml', 'rb') as f:
+ with open('index.xml', 'rb') as f:
xml = clean_ascii_chars(f.read())
PDFDocument(xml, self.opts, self.log)
return os.path.join(os.getcwd(), 'metadata.opf')
@@ -66,12 +66,12 @@ class PDFInput(InputFormatPlugin):
opf.create_spine(['index.html'])
log.debug('Rendering manifest...')
- with lopen('metadata.opf', 'wb') as opffile:
+ with open('metadata.opf', 'wb') as opffile:
opf.render(opffile)
if os.path.exists('toc.ncx'):
ncxid = opf.manifest.id_for_path('toc.ncx')
if ncxid:
- with lopen('metadata.opf', 'r+b') as f:
+ with open('metadata.opf', 'r+b') as f:
raw = f.read().replace(b' 1:
# Decouple this file from its links
os.unlink(dest)
- with lopen(dest, 'wb') as f:
+ with open(dest, 'wb') as f:
f.write(data)
def filesize(self, name):
@@ -1061,7 +1061,7 @@ class Container(ContainerBase): # {{{
this will commit the file if it is dirtied and remove it from the parse
cache. You must finish with this file before accessing the parsed
version of it again, or bad things will happen. '''
- return lopen(self.get_file_path_for_processing(name, mode not in {'r', 'rb'}), mode)
+ return open(self.get_file_path_for_processing(name, mode not in {'r', 'rb'}), mode)
def commit(self, outpath=None, keep_parsed=False):
'''
@@ -1079,7 +1079,7 @@ class Container(ContainerBase): # {{{
mismatches = []
for name, path in iteritems(self.name_path_map):
opath = other.name_path_map[name]
- with lopen(path, 'rb') as f1, lopen(opath, 'rb') as f2:
+ with open(path, 'rb') as f1, open(opath, 'rb') as f2:
if f1.read() != f2.read():
mismatches.append('The file %s is not the same'%name)
return '\n'.join(mismatches)
@@ -1172,7 +1172,7 @@ class EpubContainer(Container):
if fname is not None:
shutil.copy(os.path.join(dirpath, fname), os.path.join(base, fname))
else:
- with lopen(self.pathtoepub, 'rb') as stream:
+ with open(self.pathtoepub, 'rb') as stream:
try:
zf = ZipFile(stream)
zf.extractall(tdir)
@@ -1399,12 +1399,12 @@ class EpubContainer(Container):
if err.errno != errno.EEXIST:
raise
for fname in filenames:
- with lopen(os.path.join(dirpath, fname), 'rb') as src, lopen(os.path.join(base, fname), 'wb') as dest:
+ with open(os.path.join(dirpath, fname), 'rb') as src, open(os.path.join(base, fname), 'wb') as dest:
shutil.copyfileobj(src, dest)
else:
from calibre.ebooks.tweak import zip_rebuilder
- with lopen(join(self.root, 'mimetype'), 'wb') as f:
+ with open(join(self.root, 'mimetype'), 'wb') as f:
et = guess_type('a.epub')
if not isinstance(et, bytes):
et = et.encode('ascii')
@@ -1434,7 +1434,7 @@ class InvalidMobi(InvalidBook):
def do_explode(path, dest):
from calibre.ebooks.mobi.reader.mobi6 import MobiReader
from calibre.ebooks.mobi.reader.mobi8 import Mobi8Reader
- with lopen(path, 'rb') as stream:
+ with open(path, 'rb') as stream:
mr = MobiReader(stream, default_log, None, None)
with CurrentDir(dest):
@@ -1494,7 +1494,7 @@ class AZW3Container(Container):
tdir = PersistentTemporaryDirectory('_azw3_container')
tdir = os.path.abspath(os.path.realpath(tdir))
self.root = tdir
- with lopen(pathtoazw3, 'rb') as stream:
+ with open(pathtoazw3, 'rb') as stream:
raw = stream.read(3)
if raw == b'TPZ':
raise InvalidMobi(_('This is not a MOBI file. It is a Topaz file.'))
diff --git a/src/calibre/ebooks/oeb/polish/cover.py b/src/calibre/ebooks/oeb/polish/cover.py
index 46dc869e30..3b9c94f969 100644
--- a/src/calibre/ebooks/oeb/polish/cover.py
+++ b/src/calibre/ebooks/oeb/polish/cover.py
@@ -31,7 +31,7 @@ def set_azw3_cover(container, cover_path, report, options=None):
container.insert_into_xml(guide, guide.makeelement(
OPF('reference'), href=href, type='cover'))
if not existing_image:
- with lopen(cover_path, 'rb') as src, container.open(name, 'wb') as dest:
+ with open(cover_path, 'rb') as src, container.open(name, 'wb') as dest:
shutil.copyfileobj(src, dest)
container.dirty(container.opf_name)
report(_('Cover updated') if found else _('Cover inserted'))
@@ -350,7 +350,7 @@ def create_epub_cover(container, cover_path, existing_image, options=None):
if callable(cover_path):
cover_path('write_image', dest)
else:
- with lopen(cover_path, 'rb') as src:
+ with open(cover_path, 'rb') as src:
shutil.copyfileobj(src, dest)
if options is None:
opts = load_defaults('epub_output')
@@ -374,7 +374,7 @@ def create_epub_cover(container, cover_path, existing_image, options=None):
if existing_image:
width, height = identify(container.raw_data(existing_image, decode=False))[1:]
else:
- with lopen(cover_path, 'rb') as csrc:
+ with open(cover_path, 'rb') as csrc:
width, height = identify(csrc)[1:]
except:
container.log.exception("Failed to get width and height of cover")
diff --git a/src/calibre/ebooks/oeb/polish/download.py b/src/calibre/ebooks/oeb/polish/download.py
index 1ee8e42098..ec409e96d1 100644
--- a/src/calibre/ebooks/oeb/polish/download.py
+++ b/src/calibre/ebooks/oeb/polish/download.py
@@ -111,7 +111,7 @@ def download_one(tdir, timeout, progress_report, data_uri_map, url):
path = unquote(purl.path)
if iswindows and path.startswith('/'):
path = path[1:]
- src = lopen(path, 'rb')
+ src = open(path, 'rb')
filename = os.path.basename(path)
sz = (src.seek(0, os.SEEK_END), src.tell(), src.seek(0))[1]
elif purl.scheme == 'data':
@@ -167,7 +167,7 @@ def download_external_resources(container, urls, timeout=60, progress_report=lam
for ok, result in pool.imap_unordered(partial(download_one, tdir, timeout, progress_report, data_uri_map), urls):
if ok:
url, suggested_filename, downloaded_file, mt = result
- with lopen(downloaded_file, 'rb') as src:
+ with open(downloaded_file, 'rb') as src:
name = container.add_file(suggested_filename, src, mt, modify_name_if_needed=True)
replacements[url] = name
else:
diff --git a/src/calibre/ebooks/oeb/polish/images.py b/src/calibre/ebooks/oeb/polish/images.py
index f92a82e3be..93b76ec80d 100644
--- a/src/calibre/ebooks/oeb/polish/images.py
+++ b/src/calibre/ebooks/oeb/polish/images.py
@@ -51,12 +51,12 @@ class Worker(Thread):
else:
func = partial(encode_jpeg, quality=self.jpeg_quality)
before = os.path.getsize(path)
- with lopen(path, 'rb') as f:
+ with open(path, 'rb') as f:
old_data = f.read()
func(path)
after = os.path.getsize(path)
if after >= before:
- with lopen(path, 'wb') as f:
+ with open(path, 'wb') as f:
f.write(old_data)
after = before
self.results[name] = (True, (before, after))
diff --git a/src/calibre/ebooks/oeb/polish/tests/base.py b/src/calibre/ebooks/oeb/polish/tests/base.py
index 8cffaddd3b..6684d33627 100644
--- a/src/calibre/ebooks/oeb/polish/tests/base.py
+++ b/src/calibre/ebooks/oeb/polish/tests/base.py
@@ -55,7 +55,7 @@ def get_simple_book(fmt='epub'):
if needs_recompile(ans, src):
with TemporaryDirectory('bpt') as tdir:
with CurrentDir(tdir):
- with lopen(src, 'rb') as sf:
+ with open(src, 'rb') as sf:
raw = sf.read().decode('utf-8')
raw = add_resources(raw, {
'LMONOI': P('fonts/liberation/LiberationMono-Italic.ttf'),
@@ -65,7 +65,7 @@ def get_simple_book(fmt='epub'):
})
shutil.copy2(I('lt.png'), '.')
x = 'index.html'
- with lopen(x, 'wb') as f:
+ with open(x, 'wb') as f:
f.write(raw.encode('utf-8'))
build_book(x, ans, args=[
'--level1-toc=//h:h2', '--language=en', '--authors=Kovid Goyal', '--cover=lt.png'])
@@ -78,9 +78,9 @@ def get_split_book(fmt='epub'):
src = os.path.join(os.path.dirname(__file__), 'split.html')
if needs_recompile(ans, src):
x = src.replace('split.html', 'index.html')
- raw = lopen(src, 'rb').read().decode('utf-8')
+ raw = open(src, 'rb').read().decode('utf-8')
try:
- with lopen(x, 'wb') as f:
+ with open(x, 'wb') as f:
f.write(raw.encode('utf-8'))
build_book(x, ans, args=['--level1-toc=//h:h2', '--language=en', '--authors=Kovid Goyal',
'--cover=' + I('lt.png')])
diff --git a/src/calibre/ebooks/oeb/polish/tests/parsing.py b/src/calibre/ebooks/oeb/polish/tests/parsing.py
index 25a8e65430..8f04f8a7d3 100644
--- a/src/calibre/ebooks/oeb/polish/tests/parsing.py
+++ b/src/calibre/ebooks/oeb/polish/tests/parsing.py
@@ -214,7 +214,7 @@ def timing():
from calibre.utils.monotonic import monotonic
from html5lib import parse as vanilla
filename = sys.argv[-1]
- with lopen(filename, 'rb') as f:
+ with open(filename, 'rb') as f:
raw = f.read()
raw = xml_to_unicode(raw)[0]
diff --git a/src/calibre/ebooks/pdb/plucker/reader.py b/src/calibre/ebooks/pdb/plucker/reader.py
index 35a45c8a5c..4a9ac3313e 100644
--- a/src/calibre/ebooks/pdb/plucker/reader.py
+++ b/src/calibre/ebooks/pdb/plucker/reader.py
@@ -412,7 +412,7 @@ class Reader(FormatReader):
for col in row:
if col not in images:
raise Exception('Image with uid: %s missing.' % col)
- w, h = identify(lopen('%s.jpg' % col, 'rb'))[1:]
+ w, h = identify(open('%s.jpg' % col, 'rb'))[1:]
row_width += w
if col_height < h:
col_height = h
@@ -427,14 +427,14 @@ class Reader(FormatReader):
x_off = 0
largest_height = 0
for col in row:
- im = image_from_data(lopen('%s.jpg' % col, 'rb').read())
+ im = image_from_data(open('%s.jpg' % col, 'rb').read())
canvas.compose(im, x_off, y_off)
w, h = im.width(), im.height()
x_off += w
if largest_height < h:
largest_height = h
y_off += largest_height
- with lopen('%s.jpg' % uid) as out:
+ with open('%s.jpg' % uid) as out:
out.write(canvas.export(compression_quality=70))
self.log.debug(f'Wrote composite image with uid {uid} to images/{uid}.jpg')
except Exception as e:
diff --git a/src/calibre/ebooks/pdf/pdftohtml.py b/src/calibre/ebooks/pdf/pdftohtml.py
index 3e8145b977..40eac81a63 100644
--- a/src/calibre/ebooks/pdf/pdftohtml.py
+++ b/src/calibre/ebooks/pdf/pdftohtml.py
@@ -46,7 +46,7 @@ def pdftohtml(output_dir, pdf_path, no_images, as_xml=False):
pdfsrc = os.path.join(output_dir, 'src.pdf')
index = os.path.join(output_dir, 'index.'+('xml' if as_xml else 'html'))
- with lopen(pdf_path, 'rb') as src, lopen(pdfsrc, 'wb') as dest:
+ with open(pdf_path, 'rb') as src, open(pdfsrc, 'wb') as dest:
shutil.copyfileobj(src, dest)
with CurrentDir(output_dir):
@@ -78,7 +78,7 @@ def pdftohtml(output_dir, pdf_path, no_images, as_xml=False):
ret = eintr_retry_call(p.wait)
logf.flush()
logf.close()
- out = lopen(logf.name, 'rb').read().decode('utf-8', 'replace').strip()
+ out = open(logf.name, 'rb').read().decode('utf-8', 'replace').strip()
if ret != 0:
raise ConversionError('pdftohtml failed with return code: %d\n%s' % (ret, out))
if out:
@@ -88,7 +88,7 @@ def pdftohtml(output_dir, pdf_path, no_images, as_xml=False):
raise DRMError()
if not as_xml:
- with lopen(index, 'r+b') as i:
+ with open(index, 'r+b') as i:
raw = i.read().decode('utf-8', 'replace')
raw = flip_images(raw)
raw = raw.replace('\n '
- with lopen(attachment, 'rb') as f:
+ with open(attachment, 'rb') as f:
msg = compose_mail(from_, to, text, subject, f, aname)
efrom = extract_email_address(from_)
eto = []
diff --git a/src/calibre/gui2/icon_theme.py b/src/calibre/gui2/icon_theme.py
index ff2fca785c..15a7b3e0a7 100644
--- a/src/calibre/gui2/icon_theme.py
+++ b/src/calibre/gui2/icon_theme.py
@@ -187,7 +187,7 @@ def create_cover(report=None, icons=(), cols=5, size=120, padding=16, darkbg=Fal
ipath = os.path.join(report.path, report.name_map[icon])
else:
ipath = I(icon, allow_user_override=False)
- with lopen(ipath, 'rb') as f:
+ with open(ipath, 'rb') as f:
img = image_from_data(f.read())
scaled, nwidth, nheight = fit_image(img.width(), img.height(), size, size)
img = img.scaled(int(nwidth), int(nheight), Qt.AspectRatioMode.IgnoreAspectRatio, Qt.TransformationMode.SmoothTransformation)
@@ -403,7 +403,7 @@ def create_themeball(report, theme_metadata, progress=None, abort=None):
with ZipFile(buf, 'w') as zf:
for name in report.name_map:
srcpath = os.path.join(report.path, name)
- with lopen(srcpath, 'rb') as f:
+ with open(srcpath, 'rb') as f:
zf.writestr(name, f.read(), compression=ZIP_STORED)
buf.seek(0)
icon_zip_data = buf
@@ -418,7 +418,7 @@ def create_themeball(report, theme_metadata, progress=None, abort=None):
if abort is not None and abort.is_set():
return None, None, None
with ZipFile(buf, 'w') as zf:
- with lopen(os.path.join(report.path, THEME_METADATA), 'rb') as f:
+ with open(os.path.join(report.path, THEME_METADATA), 'rb') as f:
zf.writestr(prefix + '/' + THEME_METADATA, f.read())
zf.writestr(prefix + '/' + THEME_COVER, create_cover(report, darkbg=theme_metadata.get('color_palette') == 'dark'))
zf.writestr(prefix + '/' + 'icons.zip.xz', compressed, compression=ZIP_STORED)
@@ -450,7 +450,7 @@ def create_theme(folder=None, parent=None):
[(_('ZIP files'), ['zip'])], initial_filename=prefix + '.zip')
if not dest:
return
- with lopen(dest, 'wb') as f:
+ with open(dest, 'wb') as f:
f.write(raw)
if use_in_calibre:
diff --git a/src/calibre/gui2/main.py b/src/calibre/gui2/main.py
index 22e0f1f252..7e573023a5 100644
--- a/src/calibre/gui2/main.py
+++ b/src/calibre/gui2/main.py
@@ -385,8 +385,8 @@ def run_in_debug_mode():
fd, logpath = tempfile.mkstemp('.txt')
os.close(fd)
run_calibre_debug(
- '--gui-debug', logpath, stdout=lopen(logpath, 'wb'),
- stderr=subprocess.STDOUT, stdin=lopen(os.devnull, 'rb'))
+ '--gui-debug', logpath, stdout=open(logpath, 'wb'),
+ stderr=subprocess.STDOUT, stdin=open(os.devnull, 'rb'))
def run_gui(opts, args, app, gui_debug=None):
diff --git a/src/calibre/gui2/preferences/coloring.py b/src/calibre/gui2/preferences/coloring.py
index ed79a9e498..a1df13c6c0 100644
--- a/src/calibre/gui2/preferences/coloring.py
+++ b/src/calibre/gui2/preferences/coloring.py
@@ -1268,14 +1268,14 @@ class EditRules(QWidget): # {{{
data = json.dumps(rules, indent=2)
if not isinstance(data, bytes):
data = data.encode('utf-8')
- with lopen(path, 'wb') as f:
+ with open(path, 'wb') as f:
f.write(data)
def import_rules(self):
files = choose_files(self, 'import-coloring-rules', _('Choose file to import from'),
filters=[(_('Rules'), ['rules'])], all_files=False, select_only_single_file=True)
if files:
- with lopen(files[0], 'rb') as f:
+ with open(files[0], 'rb') as f:
raw = f.read()
try:
rules = json.loads(raw)
diff --git a/src/calibre/gui2/preferences/server.py b/src/calibre/gui2/preferences/server.py
index 5323c4ccec..a49a9848fc 100644
--- a/src/calibre/gui2/preferences/server.py
+++ b/src/calibre/gui2/preferences/server.py
@@ -940,7 +940,7 @@ class CustomList(QWidget): # {{{
paths = choose_files(self, 'custom-list-template', _('Choose template file'),
filters=[(_('Template files'), ['json'])], all_files=False, select_only_single_file=True)
if paths:
- with lopen(paths[0], 'rb') as f:
+ with open(paths[0], 'rb') as f:
raw = f.read()
self.current_template = self.deserialize(raw)
@@ -950,7 +950,7 @@ class CustomList(QWidget): # {{{
filters=[(_('Template files'), ['json'])], initial_filename='custom-list-template.json')
if path:
raw = self.serialize(self.current_template)
- with lopen(path, 'wb') as f:
+ with open(path, 'wb') as f:
f.write(as_bytes(raw))
def thumbnail_state_changed(self):
@@ -1003,7 +1003,7 @@ class CustomList(QWidget): # {{{
raise
else:
raw = self.serialize(template)
- with lopen(custom_list_template.path, 'wb') as f:
+ with open(custom_list_template.path, 'wb') as f:
f.write(as_bytes(raw))
return True
@@ -1165,7 +1165,7 @@ class SearchTheInternet(QWidget):
return False
cu = self.current_urls
if cu:
- with lopen(search_the_net_urls.path, 'wb') as f:
+ with open(search_the_net_urls.path, 'wb') as f:
f.write(self.serialized_urls.encode('utf-8'))
else:
try:
@@ -1180,14 +1180,14 @@ class SearchTheInternet(QWidget):
self, 'search-net-urls', _('Choose URLs file'),
filters=[(_('URL files'), ['json'])], initial_filename='search-urls.json')
if path:
- with lopen(path, 'wb') as f:
+ with open(path, 'wb') as f:
f.write(self.serialized_urls.encode('utf-8'))
def import_urls(self):
paths = choose_files(self, 'search-net-urls', _('Choose URLs file'),
filters=[(_('URL files'), ['json'])], all_files=False, select_only_single_file=True)
if paths:
- with lopen(paths[0], 'rb') as f:
+ with open(paths[0], 'rb') as f:
items = json.loads(f.read())
[self.append_item(x) for x in items]
self.changed_signal.emit()
diff --git a/src/calibre/gui2/save.py b/src/calibre/gui2/save.py
index a59e33ddde..9c49a897df 100644
--- a/src/calibre/gui2/save.py
+++ b/src/calibre/gui2/save.py
@@ -233,7 +233,7 @@ class Saver(QObject):
fname = os.path.join(self.tdir, '%d.jpg' % book_id)
if fname:
- with lopen(fname, 'wb') as f:
+ with open(fname, 'wb') as f:
f.write(cdata)
if self.opts.update_metadata:
d['cover'] = fname
@@ -245,7 +245,7 @@ class Saver(QObject):
fname = os.path.join(self.tdir, '%d.opf' % book_id)
if fname:
opf = metadata_to_opf(mi)
- with lopen(fname, 'wb') as f:
+ with open(fname, 'wb') as f:
f.write(opf)
if self.opts.update_metadata:
d['opf'] = fname
@@ -275,7 +275,7 @@ class Saver(QObject):
def write_fmt(self, book_id, fmt, base_path):
fmtpath = base_path + os.extsep + fmt
written = False
- with lopen(fmtpath, 'w+b') as f:
+ with open(fmtpath, 'w+b') as f:
try:
self.db.copy_format_to(book_id, fmt, f)
written = True
diff --git a/src/calibre/gui2/tweak_book/boss.py b/src/calibre/gui2/tweak_book/boss.py
index 23ce37a42d..3785c83ec3 100644
--- a/src/calibre/gui2/tweak_book/boss.py
+++ b/src/calibre/gui2/tweak_book/boss.py
@@ -1572,7 +1572,7 @@ class Boss(QObject):
name_map = json.loads(bytes(md.data(FILE_COPY_MIME)))
container = current_container()
for name, (path, mt) in iteritems(name_map):
- with lopen(path, 'rb') as f:
+ with open(path, 'rb') as f:
container.add_file(name, f.read(), media_type=mt, modify_name_if_needed=True)
self.apply_container_update_to_gui()
diff --git a/src/calibre/gui2/tweak_book/editor/smarts/html.py b/src/calibre/gui2/tweak_book/editor/smarts/html.py
index 733fc66e95..310bfd2ee7 100644
--- a/src/calibre/gui2/tweak_book/editor/smarts/html.py
+++ b/src/calibre/gui2/tweak_book/editor/smarts/html.py
@@ -876,7 +876,7 @@ class Smarts(NullSmarts):
if __name__ == '__main__': # {{{
from calibre.gui2.tweak_book.editor.widget import launch_editor
if sys.argv[-1].endswith('.html'):
- raw = lopen(sys.argv[-1], 'rb').read().decode('utf-8')
+ raw = open(sys.argv[-1], 'rb').read().decode('utf-8')
else:
raw = '''\
diff --git a/src/calibre/gui2/tweak_book/editor/text.py b/src/calibre/gui2/tweak_book/editor/text.py
index 74584c139d..7c51e19bc7 100644
--- a/src/calibre/gui2/tweak_book/editor/text.py
+++ b/src/calibre/gui2/tweak_book/editor/text.py
@@ -180,7 +180,7 @@ class TextEdit(PlainTextEdit):
name = path
else:
name = get_name(os.path.basename(path))
- with lopen(path, 'rb') as f:
+ with open(path, 'rb') as f:
name = add_file(name, f.read(), mt)
href = get_href(name)
if mt.startswith('image/'):
diff --git a/src/calibre/gui2/ui.py b/src/calibre/gui2/ui.py
index afdcdfa8e7..a9f98a0aee 100644
--- a/src/calibre/gui2/ui.py
+++ b/src/calibre/gui2/ui.py
@@ -77,12 +77,12 @@ def add_quick_start_guide(library_view, refresh_cover_browser=None):
gprefs['quick_start_guide_added'] = True
imgbuf = BytesIO(calibre_cover2(_('Quick Start Guide'), ''))
try:
- with lopen(P('quick_start/%s.epub' % l), 'rb') as src:
+ with open(P('quick_start/%s.epub' % l), 'rb') as src:
buf = BytesIO(src.read())
except OSError as err:
if err.errno != errno.ENOENT:
raise
- with lopen(P('quick_start/eng.epub'), 'rb') as src:
+ with open(P('quick_start/eng.epub'), 'rb') as src:
buf = BytesIO(src.read())
safe_replace(buf, 'images/cover.jpg', imgbuf)
buf.seek(0)
diff --git a/src/calibre/gui2/viewer/bookmarks.py b/src/calibre/gui2/viewer/bookmarks.py
index 16483bb4ff..73e988a359 100644
--- a/src/calibre/gui2/viewer/bookmarks.py
+++ b/src/calibre/gui2/viewer/bookmarks.py
@@ -300,7 +300,7 @@ class BookmarkManager(QWidget):
data = json.dumps({'type': 'bookmarks', 'entries': bm}, indent=True)
if not isinstance(data, bytes):
data = data.encode('utf-8')
- with lopen(filename, 'wb') as fileobj:
+ with open(filename, 'wb') as fileobj:
fileobj.write(data)
def import_bookmarks(self):
@@ -311,7 +311,7 @@ class BookmarkManager(QWidget):
filename = files[0]
imported = None
- with lopen(filename, 'rb') as fileobj:
+ with open(filename, 'rb') as fileobj:
imported = json.load(fileobj)
def import_old_bookmarks(imported):
diff --git a/src/calibre/gui2/viewer/convert_book.py b/src/calibre/gui2/viewer/convert_book.py
index bae919fc39..fc9601f81c 100644
--- a/src/calibre/gui2/viewer/convert_book.py
+++ b/src/calibre/gui2/viewer/convert_book.py
@@ -186,7 +186,7 @@ def do_convert(path, temp_path, key, instance):
)))
p.stdin.close()
if p.wait() != 0:
- with lopen(logpath, 'rb') as logf:
+ with open(logpath, 'rb') as logf:
worker_output = logf.read().decode('utf-8', 'replace')
raise ConversionFailure(path, worker_output)
finally:
diff --git a/src/calibre/gui2/viewer/main.py b/src/calibre/gui2/viewer/main.py
index f9cc69cdc2..3a9dcb45f4 100644
--- a/src/calibre/gui2/viewer/main.py
+++ b/src/calibre/gui2/viewer/main.py
@@ -182,7 +182,7 @@ def main(args=sys.argv):
processed_args.append(arg)
if internal_book_data_path:
try:
- with lopen(internal_book_data_path, 'rb') as f:
+ with open(internal_book_data_path, 'rb') as f:
internal_book_data = json.load(f)
finally:
try:
diff --git a/src/calibre/gui2/viewer/web_view.py b/src/calibre/gui2/viewer/web_view.py
index 9ec216ed3c..a75a3db420 100644
--- a/src/calibre/gui2/viewer/web_view.py
+++ b/src/calibre/gui2/viewer/web_view.py
@@ -103,7 +103,7 @@ def handle_mathjax_request(rq, name):
if path.startswith(mathjax_dir):
mt = guess_type(name)
try:
- with lopen(path, 'rb') as f:
+ with open(path, 'rb') as f:
raw = f.read()
except OSError as err:
prints(f"Failed to get mathjax file: {name} with error: {err}", file=sys.stderr)
diff --git a/src/calibre/gui2/widgets.py b/src/calibre/gui2/widgets.py
index 2daed5bc0e..ae00f6feb1 100644
--- a/src/calibre/gui2/widgets.py
+++ b/src/calibre/gui2/widgets.py
@@ -254,7 +254,7 @@ class ImageDropMixin: # {{{
d.start_download()
if d.err is None:
pmap = QPixmap()
- with lopen(d.fpath, 'rb') as f:
+ with open(d.fpath, 'rb') as f:
data = f.read()
pmap.loadFromData(data)
if not pmap.isNull():
diff --git a/src/calibre/gui2/widgets2.py b/src/calibre/gui2/widgets2.py
index 95203ed1c6..7a57ba31a2 100644
--- a/src/calibre/gui2/widgets2.py
+++ b/src/calibre/gui2/widgets2.py
@@ -569,7 +569,7 @@ class HTMLDisplay(QTextBrowser):
if qurl.isLocalFile():
path = qurl.toLocalFile()
try:
- with lopen(path, 'rb') as f:
+ with open(path, 'rb') as f:
data = f.read()
except OSError:
if path.rpartition('.')[-1].lower() in {'jpg', 'jpeg', 'gif', 'png', 'bmp', 'webp'}:
diff --git a/src/calibre/library/caches.py b/src/calibre/library/caches.py
index fc4434b799..197cc736f8 100644
--- a/src/calibre/library/caches.py
+++ b/src/calibre/library/caches.py
@@ -114,7 +114,7 @@ class MetadataBackup(Thread): # {{{
self.break_cycles()
def write(self, path, raw):
- with lopen(path, 'wb') as f:
+ with open(path, 'wb') as f:
f.write(raw)
diff --git a/src/calibre/library/catalogs/epub_mobi_builder.py b/src/calibre/library/catalogs/epub_mobi_builder.py
index 18c706dde9..42fa7f40dd 100644
--- a/src/calibre/library/catalogs/epub_mobi_builder.py
+++ b/src/calibre/library/catalogs/epub_mobi_builder.py
@@ -3709,7 +3709,7 @@ class CatalogBuilder:
# Write the OPF file
pretty_opf(root), pretty_xml_tree(root)
output = etree.tostring(root, encoding='utf-8')
- with lopen(f"{self.catalog_path}/{self.opts.basename}.opf", 'wb') as outfile:
+ with open(f"{self.catalog_path}/{self.opts.basename}.opf", 'wb') as outfile:
outfile.write(output.strip())
def generate_rating_string(self, book):
@@ -3885,7 +3885,7 @@ class CatalogBuilder:
pass
# Generate crc for current cover
- with lopen(title['cover'], 'rb') as f:
+ with open(title['cover'], 'rb') as f:
data = f.read()
cover_crc = hex(zlib.crc32(data))
@@ -3909,7 +3909,7 @@ class CatalogBuilder:
# Save thumb for catalog. If invalid data, error returns to generate_thumbnails()
thumb_data = scale_image(data,
width=self.thumb_width, height=self.thumb_height)[-1]
- with lopen(os.path.join(image_dir, thumb_file), 'wb') as f:
+ with open(os.path.join(image_dir, thumb_file), 'wb') as f:
f.write(thumb_data)
# Save thumb to archive
@@ -4378,5 +4378,5 @@ class CatalogBuilder:
self.update_progress_full_step(_("Saving NCX"))
pretty_xml_tree(self.ncx_root)
ncx = etree.tostring(self.ncx_root, encoding='utf-8')
- with lopen(f"{self.catalog_path}/{self.opts.basename}.ncx", 'wb') as outfile:
+ with open(f"{self.catalog_path}/{self.opts.basename}.ncx", 'wb') as outfile:
outfile.write(ncx)
diff --git a/src/calibre/library/database.py b/src/calibre/library/database.py
index f3c0b7dd4c..16757b20ac 100644
--- a/src/calibre/library/database.py
+++ b/src/calibre/library/database.py
@@ -1355,7 +1355,7 @@ ALTER TABLE books ADD COLUMN isbn TEXT DEFAULT "" COLLATE NOCASE;
id = obj.lastrowid
self.conn.commit()
self.set_metadata(id, mi)
- stream = path if hasattr(path, 'read') else lopen(path, 'rb')
+ stream = path if hasattr(path, 'read') else open(path, 'rb')
stream.seek(0, 2)
usize = stream.tell()
stream.seek(0)
diff --git a/src/calibre/library/database2.py b/src/calibre/library/database2.py
index 1632921287..5b186aa0ea 100644
--- a/src/calibre/library/database2.py
+++ b/src/calibre/library/database2.py
@@ -756,10 +756,10 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns):
path = os.path.join(self.library_path, self.path(id, index_is_id=True), 'cover.jpg')
if os.access(path, os.R_OK):
try:
- f = lopen(path, 'rb')
+ f = open(path, 'rb')
except OSError:
time.sleep(0.2)
- f = lopen(path, 'rb')
+ f = open(path, 'rb')
with f:
if as_path:
pt = PersistentTemporaryFile('_dbcover.jpg')
@@ -873,7 +873,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns):
continue
try:
raw = metadata_to_opf(mi)
- with lopen(path, 'wb') as f:
+ with open(path, 'wb') as f:
f.write(raw)
if remove_from_dirtied:
self.clear_dirtied(book_id, sequence)
@@ -1312,7 +1312,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns):
if path is None:
raise NoSuchFormat('Record %d has no fmt: %s'%(id_, fmt))
sha = hashlib.sha256()
- with lopen(path, 'rb') as f:
+ with open(path, 'rb') as f:
while True:
raw = f.read(SPOOL_SIZE)
sha.update(raw)
@@ -1408,7 +1408,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns):
windows_atomic_move.copy_path_to(path, dest)
else:
if hasattr(dest, 'write'):
- with lopen(path, 'rb') as f:
+ with open(path, 'rb') as f:
shutil.copyfileobj(f, dest)
if hasattr(dest, 'flush'):
dest.flush()
@@ -1427,7 +1427,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns):
return
except:
pass
- with lopen(path, 'rb') as f, lopen(dest, 'wb') as d:
+ with open(path, 'rb') as f, open(dest, 'wb') as d:
shutil.copyfileobj(f, d)
def copy_cover_to(self, index, dest, index_is_id=False,
@@ -1458,10 +1458,10 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns):
else:
if os.access(path, os.R_OK):
try:
- f = lopen(path, 'rb')
+ f = open(path, 'rb')
except OSError:
time.sleep(0.2)
- f = lopen(path, 'rb')
+ f = open(path, 'rb')
with f:
if hasattr(dest, 'write'):
shutil.copyfileobj(f, dest)
@@ -1475,7 +1475,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns):
return True
except:
pass
- with lopen(dest, 'wb') as d:
+ with open(dest, 'wb') as d:
shutil.copyfileobj(f, d)
return True
return False
@@ -1500,7 +1500,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns):
'''
path = self.format_abspath(index, format, index_is_id=index_is_id)
if path is not None:
- with lopen(path, mode) as f:
+ with open(path, mode) as f:
if as_path:
if preserve_filename:
bd = base_dir()
@@ -1511,7 +1511,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns):
pass
fname = os.path.basename(path)
ret = os.path.join(d, fname)
- with lopen(ret, 'wb') as f2:
+ with open(ret, 'wb') as f2:
shutil.copyfileobj(f, f2)
else:
with PersistentTemporaryFile('.'+format.lower()) as pt:
@@ -1532,7 +1532,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns):
path=None, notify=True, replace=True):
npath = self.run_import_plugins(fpath, format)
format = os.path.splitext(npath)[-1].lower().replace('.', '').upper()
- stream = lopen(npath, 'rb')
+ stream = open(npath, 'rb')
format = check_ebook_format(stream, format)
id = index if index_is_id else self.id(index)
retval = self.add_format(id, format, stream, replace=replace,
@@ -1564,7 +1564,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns):
else:
if (not getattr(stream, 'name', False) or not samefile(dest,
stream.name)):
- with lopen(dest, 'wb') as f:
+ with open(dest, 'wb') as f:
shutil.copyfileobj(stream, f)
size = f.tell()
elif os.path.exists(dest):
@@ -1587,7 +1587,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns):
if opath is None:
return False
nfmt = 'ORIGINAL_'+fmt
- with lopen(opath, 'rb') as f:
+ with open(opath, 'rb') as f:
return self.add_format(book_id, nfmt, f, index_is_id=True, notify=notify)
def original_fmt(self, book_id, fmt):
@@ -1600,7 +1600,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns):
opath = self.format_abspath(book_id, original_fmt, index_is_id=True)
if opath is not None:
fmt = original_fmt.partition('_')[2]
- with lopen(opath, 'rb') as f:
+ with open(opath, 'rb') as f:
self.add_format(book_id, fmt, f, index_is_id=True, notify=False)
self.remove_format(book_id, original_fmt, index_is_id=True, notify=notify)
return True
@@ -2336,7 +2336,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns):
doit(self.set_cover, id, mi.cover_data[1], commit=False)
elif isinstance(mi.cover, string_or_bytes) and mi.cover:
if os.access(mi.cover, os.R_OK):
- with lopen(mi.cover, 'rb') as f:
+ with open(mi.cover, 'rb') as f:
raw = f.read()
if raw:
doit(self.set_cover, id, raw, commit=False)
@@ -3358,7 +3358,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns):
from calibre.ebooks.metadata.meta import get_metadata
format = os.path.splitext(path)[1][1:].lower()
- with lopen(path, 'rb') as stream:
+ with open(path, 'rb') as stream:
matches = self.data.get_matches('title', '='+title)
if matches:
tag_matches = self.data.get_matches('tags', '='+_('Catalog'))
@@ -3394,7 +3394,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns):
from calibre.ebooks.metadata.meta import get_metadata
format = os.path.splitext(path)[1][1:].lower()
- stream = path if hasattr(path, 'read') else lopen(path, 'rb')
+ stream = path if hasattr(path, 'read') else open(path, 'rb')
stream.seek(0)
mi = get_metadata(stream, format, use_libprs_metadata=False,
force_read_metadata=True)
@@ -3525,7 +3525,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns):
self.set_metadata(id, mi, commit=True, ignore_errors=True)
npath = self.run_import_plugins(path, format)
format = os.path.splitext(npath)[-1].lower().replace('.', '').upper()
- with lopen(npath, 'rb') as stream:
+ with open(npath, 'rb') as stream:
format = check_ebook_format(stream, format)
self.add_format(id, format, stream, index_is_id=True)
postimport.append((id, format))
@@ -3574,7 +3574,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns):
if import_hooks:
self.add_format_with_hooks(id, ext, path, index_is_id=True)
else:
- with lopen(path, 'rb') as f:
+ with open(path, 'rb') as f:
self.add_format(id, ext, f, index_is_id=True)
# Mark the book dirty, It probably already has been done by
# set_metadata, but probably isn't good enough
diff --git a/src/calibre/library/save_to_disk.py b/src/calibre/library/save_to_disk.py
index 24a6625c11..e6d19dca71 100644
--- a/src/calibre/library/save_to_disk.py
+++ b/src/calibre/library/save_to_disk.py
@@ -341,13 +341,13 @@ def do_save_book_to_disk(db, book_id, mi, plugboards,
cdata = db.cover(book_id)
if cdata:
cpath = base_path + '.jpg'
- with lopen(cpath, 'wb') as f:
+ with open(cpath, 'wb') as f:
f.write(cdata)
mi.cover = base_name+'.jpg'
if opts.write_opf:
from calibre.ebooks.metadata.opf2 import metadata_to_opf
opf = metadata_to_opf(mi)
- with lopen(base_path+'.opf', 'wb') as f:
+ with open(base_path+'.opf', 'wb') as f:
f.write(opf)
finally:
mi.cover, mi.pubdate, mi.timestamp = originals
@@ -363,7 +363,7 @@ def do_save_book_to_disk(db, book_id, mi, plugboards,
except NoSuchFormat:
continue
if opts.update_metadata:
- with lopen(fmt_path, 'r+b') as stream:
+ with open(fmt_path, 'r+b') as stream:
update_metadata(mi, fmt, stream, plugboards, cdata)
return not formats_written, book_id, mi.title
@@ -423,7 +423,7 @@ def read_serialized_metadata(data):
mi.cover, mi.cover_data = None, (None, None)
cdata = None
if 'cover' in data:
- with lopen(data['cover'], 'rb') as f:
+ with open(data['cover'], 'rb') as f:
cdata = f.read()
return mi, cdata
@@ -441,7 +441,7 @@ def update_serialized_metadata(book, common_data=None):
for fmt, fmtpath in zip(fmts, book['fmts']):
try:
- with lopen(fmtpath, 'r+b') as stream:
+ with open(fmtpath, 'r+b') as stream:
update_metadata(mi, fmt, stream, (), cdata, error_report=report_error, plugboard_cache=plugboard_cache)
except Exception:
report_error(fmt, traceback.format_exc())
diff --git a/src/calibre/srv/books.py b/src/calibre/srv/books.py
index 515d296b7c..463016281b 100644
--- a/src/calibre/srv/books.py
+++ b/src/calibre/srv/books.py
@@ -148,7 +148,7 @@ def book_manifest(ctx, rd, book_id, fmt):
safe_remove(mpath, True)
try:
os.utime(mpath, None)
- with lopen(mpath, 'rb') as f:
+ with open(mpath, 'rb') as f:
ans = jsonlib.load(f)
ans['metadata'] = book_as_json(db, book_id)
user = rd.username or None
@@ -179,7 +179,7 @@ def book_file(ctx, rd, book_id, fmt, size, mtime, name):
if not mpath.startswith(base):
raise HTTPNotFound(f'No book file with hash: {bhash} and name: {name}')
try:
- return rd.filesystem_file_with_custom_etag(lopen(mpath, 'rb'), bhash, name)
+ return rd.filesystem_file_with_custom_etag(open(mpath, 'rb'), bhash, name)
except OSError as e:
if e.errno != errno.ENOENT:
raise
@@ -304,4 +304,4 @@ def mathjax(ctx, rd, which):
path = os.path.abspath(P('mathjax/' + which, allow_user_override=False))
if not path.startswith(P('mathjax', allow_user_override=False)):
raise HTTPNotFound('No MathJax file named: %s' % which)
- return rd.filesystem_file_with_constant_etag(lopen(path, 'rb'), manifest['etag'])
+ return rd.filesystem_file_with_constant_etag(open(path, 'rb'), manifest['etag'])
diff --git a/src/calibre/srv/code.py b/src/calibre/srv/code.py
index 142c5f232e..73e1d3c754 100644
--- a/src/calibre/srv/code.py
+++ b/src/calibre/srv/code.py
@@ -46,7 +46,7 @@ def index(ctx, rd):
if not p.path.endswith(b'/'):
p = p._replace(path=p.path + b'/')
raise HTTPRedirect(urlunparse(p).decode('utf-8'))
- ans_file = lopen(P('content-server/index-generated.html'), 'rb')
+ ans_file = open(P('content-server/index-generated.html'), 'rb')
if not in_develop_mode:
return ans_file
return ans_file.read().replace(b'__IN_DEVELOP_MODE__', b'1')
diff --git a/src/calibre/srv/embedded.py b/src/calibre/srv/embedded.py
index 818a798183..7a0a08a547 100644
--- a/src/calibre/srv/embedded.py
+++ b/src/calibre/srv/embedded.py
@@ -26,7 +26,7 @@ def log_paths():
def read_json(path):
try:
- with lopen(path, 'rb') as f:
+ with open(path, 'rb') as f:
raw = f.read()
except OSError as err:
if err.errno != errno.ENOENT:
diff --git a/src/calibre/srv/jobs.py b/src/calibre/srv/jobs.py
index 89ae01d22d..79f1cab431 100644
--- a/src/calibre/srv/jobs.py
+++ b/src/calibre/srv/jobs.py
@@ -72,7 +72,7 @@ class Job(Thread):
ans = ''
if self.log_path is not None:
try:
- with lopen(self.log_path, 'rb') as f:
+ with open(self.log_path, 'rb') as f:
ans = f.read()
except OSError:
pass
diff --git a/src/calibre/srv/render_book.py b/src/calibre/srv/render_book.py
index 1bf0ecad9a..4512373f52 100644
--- a/src/calibre/srv/render_book.py
+++ b/src/calibre/srv/render_book.py
@@ -416,8 +416,8 @@ class RenderManager:
self.max_workers = max_workers
def launch_worker(self):
- with lopen(os.path.join(self.tdir, f'{len(self.workers)}.json'), 'wb') as output:
- error = lopen(os.path.join(self.tdir, f'{len(self.workers)}.error'), 'wb')
+ with open(os.path.join(self.tdir, f'{len(self.workers)}.json'), 'wb') as output:
+ error = open(os.path.join(self.tdir, f'{len(self.workers)}.error'), 'wb')
p = start_pipe_worker('from calibre.srv.render_book import worker_main; worker_main()', stdout=error, stderr=error)
p.output_path = output.name
p.error_path = error.name
@@ -485,10 +485,10 @@ class RenderManager:
worker.wait()
continue
if worker.wait() != 0:
- with lopen(worker.error_path, 'rb') as f:
+ with open(worker.error_path, 'rb') as f:
error = f.read().decode('utf-8', 'replace')
else:
- with lopen(worker.output_path, 'rb') as f:
+ with open(worker.output_path, 'rb') as f:
results.append(msgpack_loads(f.read()))
if error is not None:
raise Exception('Render worker failed with error:\n' + error)
@@ -698,7 +698,7 @@ def process_exploded_book(
amap[k] = tuple(v) # needed for JSON serialization
data = as_bytes(json.dumps(book_render_data, ensure_ascii=False))
- with lopen(os.path.join(container.root, 'calibre-book-manifest.json'), 'wb') as f:
+ with open(os.path.join(container.root, 'calibre-book-manifest.json'), 'wb') as f:
f.write(data)
return container, bookmark_data
@@ -784,7 +784,7 @@ def render(pathtoebook, output_dir, book_hash=None, serialize_metadata=False, ex
if serialize_metadata:
from calibre.customize.ui import quick_metadata
from calibre.ebooks.metadata.meta import get_metadata
- with lopen(pathtoebook, 'rb') as f, quick_metadata:
+ with open(pathtoebook, 'rb') as f, quick_metadata:
mi = get_metadata(f, os.path.splitext(pathtoebook)[1][1:].lower())
book_fmt, opfpath, input_fmt = extract_book(pathtoebook, output_dir, log=default_log)
container, bookmark_data = process_exploded_book(
@@ -797,14 +797,14 @@ def render(pathtoebook, output_dir, book_hash=None, serialize_metadata=False, ex
d = metadata_as_dict(mi)
d.pop('cover_data', None)
serialize_datetimes(d), serialize_datetimes(d.get('user_metadata', {}))
- with lopen(os.path.join(output_dir, 'calibre-book-metadata.json'), 'wb') as f:
+ with open(os.path.join(output_dir, 'calibre-book-metadata.json'), 'wb') as f:
f.write(json_dumps(d))
if extract_annotations:
annotations = None
if bookmark_data:
annotations = json_dumps(tuple(get_stored_annotations(container, bookmark_data)))
if annotations:
- with lopen(os.path.join(output_dir, 'calibre-book-annotations.json'), 'wb') as f:
+ with open(os.path.join(output_dir, 'calibre-book-annotations.json'), 'wb') as f:
f.write(annotations)
diff --git a/src/calibre/srv/standalone.py b/src/calibre/srv/standalone.py
index c477a3a294..6bed06f780 100644
--- a/src/calibre/srv/standalone.py
+++ b/src/calibre/srv/standalone.py
@@ -68,10 +68,10 @@ class Server:
access_log = RotatingLog(opts.access_log, max_size=log_size)
self.handler = Handler(libraries, opts)
if opts.custom_list_template:
- with lopen(os.path.expanduser(opts.custom_list_template), 'rb') as f:
+ with open(os.path.expanduser(opts.custom_list_template), 'rb') as f:
self.handler.router.ctx.custom_list_template = json.load(f)
if opts.search_the_net_urls:
- with lopen(os.path.expanduser(opts.search_the_net_urls), 'rb') as f:
+ with open(os.path.expanduser(opts.search_the_net_urls), 'rb') as f:
self.handler.router.ctx.search_the_net_urls = json.load(f)
plugins = []
if opts.use_bonjour:
@@ -234,7 +234,7 @@ def main(args=sys.argv):
)
daemonize()
if opts.pidfile:
- with lopen(opts.pidfile, 'wb') as f:
+ with open(opts.pidfile, 'wb') as f:
f.write(str(os.getpid()).encode('ascii'))
signal.signal(signal.SIGTERM, lambda s, f: server.stop())
if not getattr(opts, 'daemonize', False) and not iswindows:
diff --git a/src/calibre/utils/exim.py b/src/calibre/utils/exim.py
index 3d5880a267..dfc8865de4 100644
--- a/src/calibre/utils/exim.py
+++ b/src/calibre/utils/exim.py
@@ -139,13 +139,13 @@ class Exporter:
rpath = os.path.relpath(fpath, path).replace(os.sep, '/')
key = f'{pkey}:{rpath}'
try:
- with lopen(fpath, 'rb') as f:
+ with open(fpath, 'rb') as f:
self.add_file(f, key)
except OSError:
if not iswindows:
raise
time.sleep(1)
- with lopen(fpath, 'rb') as f:
+ with open(fpath, 'rb') as f:
self.add_file(f, key)
files.append((key, rpath))
@@ -274,7 +274,7 @@ class Importer:
self.file_metadata = self.metadata['file_metadata']
def part(self, num):
- return lopen(self.part_map[num], 'rb')
+ return open(self.part_map[num], 'rb')
def start_file(self, key, description):
partnum, pos, size, digest, mtime = self.file_metadata[key]
@@ -287,16 +287,16 @@ class Importer:
f = self.start_file(key, relpath)
path = os.path.join(base_dir, relpath.replace('/', os.sep))
try:
- with lopen(path, 'wb') as dest:
+ with open(path, 'wb') as dest:
shutil.copyfileobj(f, dest)
except OSError:
os.makedirs(os.path.dirname(path))
- with lopen(path, 'wb') as dest:
+ with open(path, 'wb') as dest:
shutil.copyfileobj(f, dest)
f.close()
gpath = os.path.join(base_dir, 'global.py')
try:
- with lopen(gpath, 'rb') as f:
+ with open(gpath, 'rb') as f:
raw = f.read()
except OSError:
raw = b''
@@ -310,7 +310,7 @@ class Importer:
raw = c.src
if not isinstance(raw, bytes):
raw = raw.encode('utf-8')
- with lopen(gpath, 'wb') as f:
+ with open(gpath, 'wb') as f:
f.write(raw)
gprefs = JSONConfig('gui', base_path=base_dir)
gprefs['library_usage_stats'] = dict(library_usage_stats)
diff --git a/src/calibre/utils/filenames.py b/src/calibre/utils/filenames.py
index 2fe951e9e3..0e6fd58635 100644
--- a/src/calibre/utils/filenames.py
+++ b/src/calibre/utils/filenames.py
@@ -197,7 +197,7 @@ def case_preserving_open_file(path, mode='wb', mkdir_mode=0o777):
ans = fpath = cpath
else:
fname = components[-1]
- ans = lopen(os.path.join(cpath, fname), mode)
+ ans = open(os.path.join(cpath, fname), mode)
# Ensure file and all its metadata is written to disk so that subsequent
# listdir() has file name in it. I don't know if this is actually
# necessary, but given the diversity of platforms, best to be safe.
@@ -407,7 +407,7 @@ class WindowsAtomicFolderMove:
return
winutil.set_file_pointer(handle, 0, winutil.FILE_BEGIN)
- with lopen(dest, 'wb') as f:
+ with open(dest, 'wb') as f:
sz = 1024 * 1024
while True:
raw = winutil.read_file(handle, sz)
diff --git a/src/calibre/utils/fonts/scanner.py b/src/calibre/utils/fonts/scanner.py
index 17fff5d484..ca24757f40 100644
--- a/src/calibre/utils/fonts/scanner.py
+++ b/src/calibre/utils/fonts/scanner.py
@@ -253,7 +253,7 @@ class FontScanner(Thread):
path = font_or_path
if isinstance(font_or_path, dict):
path = font_or_path['path']
- with lopen(path, 'rb') as f:
+ with open(path, 'rb') as f:
return f.read()
def find_font_for_text(self, text, allowed_families={'serif', 'sans-serif'},
@@ -374,7 +374,7 @@ class FontScanner(Thread):
self.write_cache()
def read_font_metadata(self, path, fileid):
- with lopen(path, 'rb') as f:
+ with open(path, 'rb') as f:
try:
fm = FontMetadata(f)
except UnsupportedFont:
diff --git a/src/calibre/utils/fonts/utils.py b/src/calibre/utils/fonts/utils.py
index 48f7d7f344..3c589c8479 100644
--- a/src/calibre/utils/fonts/utils.py
+++ b/src/calibre/utils/fonts/utils.py
@@ -442,7 +442,7 @@ def get_font_for_text(text, candidate_font_data=None):
from calibre.utils.fonts.scanner import font_scanner
family, faces = font_scanner.find_font_for_text(text)
if faces:
- with lopen(faces[0]['path'], 'rb') as f:
+ with open(faces[0]['path'], 'rb') as f:
candidate_font_data = f.read()
return candidate_font_data
diff --git a/src/calibre/utils/hyphenation/dictionaries.py b/src/calibre/utils/hyphenation/dictionaries.py
index 7abc5d2ee0..381c80a7a3 100644
--- a/src/calibre/utils/hyphenation/dictionaries.py
+++ b/src/calibre/utils/hyphenation/dictionaries.py
@@ -65,7 +65,7 @@ def extract_dicts(cache_path):
tf = tarfile.open(dict_tarball)
else:
buf = BytesIO()
- with lopen(dict_tarball, 'rb') as f:
+ with open(dict_tarball, 'rb') as f:
data = f.read()
decompress(data, outfile=buf)
buf.seek(0)
diff --git a/src/calibre/utils/img.py b/src/calibre/utils/img.py
index 7dd1850ad9..3952f4bbb7 100644
--- a/src/calibre/utils/img.py
+++ b/src/calibre/utils/img.py
@@ -52,11 +52,11 @@ def load_jxr_data(data):
with TemporaryDirectory() as tdir:
if isinstance(tdir, bytes):
tdir = os.fsdecode(tdir)
- with lopen(os.path.join(tdir, 'input.jxr'), 'wb') as f:
+ with open(os.path.join(tdir, 'input.jxr'), 'wb') as f:
f.write(data)
cmd = [get_exe_path('JxrDecApp'), '-i', 'input.jxr', '-o', 'output.tif']
creationflags = subprocess.DETACHED_PROCESS if iswindows else 0
- subprocess.Popen(cmd, cwd=tdir, stdout=lopen(os.devnull, 'wb'), stderr=subprocess.STDOUT, creationflags=creationflags).wait()
+ subprocess.Popen(cmd, cwd=tdir, stdout=open(os.devnull, 'wb'), stderr=subprocess.STDOUT, creationflags=creationflags).wait()
i = QImage()
if not i.load(os.path.join(tdir, 'output.tif')):
raise NotImage('Failed to convert JPEG-XR image')
@@ -136,7 +136,7 @@ def image_from_data(data):
def image_from_path(path):
' Load an image from the specified path. '
- with lopen(path, 'rb') as f:
+ with open(path, 'rb') as f:
return image_from_data(f.read())
@@ -212,7 +212,7 @@ def save_image(img, path, **kw):
`image_to_data()` function. '''
fmt = path.rpartition('.')[-1]
kw['fmt'] = kw.get('fmt', fmt)
- with lopen(path, 'wb') as f:
+ with open(path, 'wb') as f:
f.write(image_to_data(image_from_data(img), **kw))
@@ -293,7 +293,7 @@ def save_cover_data_to(
changed = True
if path is None:
return image_to_data(img, compression_quality, fmt, compression_quality // 10) if changed else data
- with lopen(path, 'wb') as f:
+ with open(path, 'wb') as f:
f.write(image_to_data(img, compression_quality, fmt, compression_quality // 10) if changed else data)
# }}}
@@ -666,7 +666,7 @@ def test(): # {{{
if __name__ == '__main__': # {{{
args = sys.argv[1:]
infile = args.pop(0)
- img = image_from_data(lopen(infile, 'rb').read())
+ img = image_from_data(open(infile, 'rb').read())
func = globals()[args[0]]
kw = {}
args.pop(0)
@@ -691,6 +691,6 @@ if __name__ == '__main__': # {{{
bn = os.path.basename(infile)
outf = bn.rpartition('.')[0] + '.' + '-output' + bn.rpartition('.')[-1]
img = func(img, **kw)
- with lopen(outf, 'wb') as f:
+ with open(outf, 'wb') as f:
f.write(image_to_data(img, fmt=outf.rpartition('.')[-1]))
# }}}
diff --git a/src/calibre/utils/imghdr.py b/src/calibre/utils/imghdr.py
index 22e1e28990..e23c4f8d17 100644
--- a/src/calibre/utils/imghdr.py
+++ b/src/calibre/utils/imghdr.py
@@ -16,7 +16,7 @@ def what(file, h=None):
' Recognize image headers '
if h is None:
if isinstance(file, string_or_bytes):
- with lopen(file, 'rb') as f:
+ with open(file, 'rb') as f:
h = f.read(HSIZE)
else:
location = file.tell()
@@ -42,7 +42,7 @@ def identify(src):
needs_close = False
if isinstance(src, str):
- stream = lopen(src, 'rb')
+ stream = open(src, 'rb')
needs_close = True
elif isinstance(src, bytes):
stream = ReadOnlyFileBuffer(src)
diff --git a/src/calibre/utils/ipc/pool.py b/src/calibre/utils/ipc/pool.py
index 24de5ef0f9..a94b3ac106 100644
--- a/src/calibre/utils/ipc/pool.py
+++ b/src/calibre/utils/ipc/pool.py
@@ -352,7 +352,7 @@ def worker_main(conn):
break
if not isinstance(job, Job):
if isinstance(job, File):
- with lopen(job.name, 'rb') as f:
+ with open(job.name, 'rb') as f:
common_data = f.read()
common_data = pickle_loads(common_data)
else:
diff --git a/src/calibre/utils/ipc/server.py b/src/calibre/utils/ipc/server.py
index 07e2a25447..29766cfdae 100644
--- a/src/calibre/utils/ipc/server.py
+++ b/src/calibre/utils/ipc/server.py
@@ -193,7 +193,7 @@ class Server(Thread):
job.returncode = worker.returncode
elif os.path.exists(worker.rfile):
try:
- with lopen(worker.rfile, 'rb') as f:
+ with open(worker.rfile, 'rb') as f:
job.result = pickle_loads(f.read())
os.remove(worker.rfile)
except:
diff --git a/src/calibre/utils/ipc/worker.py b/src/calibre/utils/ipc/worker.py
index cdf3090af7..4afa8b652d 100644
--- a/src/calibre/utils/ipc/worker.py
+++ b/src/calibre/utils/ipc/worker.py
@@ -215,7 +215,7 @@ def main():
result = func(*args, **kwargs)
if result is not None:
os.makedirs(os.path.dirname(resultf), exist_ok=True)
- with lopen(resultf, 'wb') as f:
+ with open(resultf, 'wb') as f:
f.write(pickle_dumps(result))
notifier.queue.put(None)
diff --git a/src/calibre/utils/lock.py b/src/calibre/utils/lock.py
index 71ba23ffd2..c9ee5fb608 100644
--- a/src/calibre/utils/lock.py
+++ b/src/calibre/utils/lock.py
@@ -176,7 +176,7 @@ else:
def create_single_instance_mutex(name, per_user=True):
from calibre.utils.ipc import eintr_retry_call
path = singleinstance_path(name, per_user)
- f = lopen(path, 'w')
+ f = open(path, 'w')
try:
eintr_retry_call(fcntl.lockf, f.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
return partial(_clean_lock_file, f)
diff --git a/src/calibre/utils/magick/draw.py b/src/calibre/utils/magick/draw.py
index 402d6b66b8..3794dfe9e0 100644
--- a/src/calibre/utils/magick/draw.py
+++ b/src/calibre/utils/magick/draw.py
@@ -112,7 +112,7 @@ def identify(path):
(width, height, format)
or raises an Exception.
'''
- with lopen(path, 'rb') as f:
+ with open(path, 'rb') as f:
fmt, width, height = _identify(f)
return width, height, fmt
diff --git a/src/calibre/utils/magick/legacy.py b/src/calibre/utils/magick/legacy.py
index cf1544f339..651a0bd56e 100644
--- a/src/calibre/utils/magick/legacy.py
+++ b/src/calibre/utils/magick/legacy.py
@@ -40,7 +40,7 @@ class Image:
if hasattr(path_or_file, 'read'):
self.load(path_or_file.read())
else:
- with lopen(path_or_file, 'rb') as f:
+ with open(path_or_file, 'rb') as f:
self.load(f.read())
def load(self, data):
@@ -101,7 +101,7 @@ class Image:
format = ext[1:]
format = format.upper()
- with lopen(path, 'wb') as f:
+ with open(path, 'wb') as f:
f.write(self.export(format))
def compose(self, img, left=0, top=0, operation='OverCompositeOp'):
diff --git a/src/calibre/utils/rapydscript.py b/src/calibre/utils/rapydscript.py
index cb7ede3919..d228363058 100644
--- a/src/calibre/utils/rapydscript.py
+++ b/src/calibre/utils/rapydscript.py
@@ -328,7 +328,7 @@ def base_dir():
def atomic_write(base, name, content):
name = os.path.join(base, name)
tname = name + '.tmp'
- with lopen(tname, 'wb') as f:
+ with open(tname, 'wb') as f:
f.write(as_bytes(content))
atomic_rename(tname, name)
@@ -355,7 +355,7 @@ def run_rapydscript_tests():
base = base_dir()
rapydscript_dir = os.path.join(base, 'src', 'pyj')
fname = os.path.join(rapydscript_dir, 'test.pyj')
- with lopen(fname, 'rb') as f:
+ with open(fname, 'rb') as f:
js = compile_fast(f.read(), fname)
class UrlSchemeHandler(QWebEngineUrlSchemeHandler):
@@ -443,7 +443,7 @@ def compile_editor():
base = base_dir()
rapydscript_dir = os.path.join(base, 'src', 'pyj')
fname = os.path.join(rapydscript_dir, 'editor.pyj')
- with lopen(fname, 'rb') as f:
+ with open(fname, 'rb') as f:
js = set_data(compile_fast(f.read(), fname))
base = os.path.join(base, 'resources')
atomic_write(base, 'editor.js', js)
@@ -455,14 +455,14 @@ def compile_viewer():
g = {'__file__': iconf}
exec_path(iconf, g)
icons = g['merge']()
- with lopen(os.path.join(base, 'resources', 'content-server', 'reset.css'), 'rb') as f:
+ with open(os.path.join(base, 'resources', 'content-server', 'reset.css'), 'rb') as f:
reset = f.read().decode('utf-8')
html = '\n{icons}'.format(
icons=icons, reset=reset)
rapydscript_dir = os.path.join(base, 'src', 'pyj')
fname = os.path.join(rapydscript_dir, 'viewer-main.pyj')
- with lopen(fname, 'rb') as f:
+ with open(fname, 'rb') as f:
js = set_data(compile_fast(f.read(), fname))
base = os.path.join(base, 'resources')
atomic_write(base, 'viewer.js', js)
@@ -475,22 +475,22 @@ def compile_srv():
g = {'__file__': iconf}
exec_path(iconf, g)
icons = g['merge']().encode('utf-8')
- with lopen(os.path.join(base, 'resources', 'content-server', 'reset.css'), 'rb') as f:
+ with open(os.path.join(base, 'resources', 'content-server', 'reset.css'), 'rb') as f:
reset = f.read()
rapydscript_dir = os.path.join(base, 'src', 'pyj')
rb = os.path.join(base, 'src', 'calibre', 'srv', 'render_book.py')
- with lopen(rb, 'rb') as f:
+ with open(rb, 'rb') as f:
rv = str(int(re.search(br'^RENDER_VERSION\s+=\s+(\d+)', f.read(), re.M).group(1)))
mathjax_version = json.loads(P('mathjax/manifest.json', data=True, allow_user_override=False))['etag']
base = os.path.join(base, 'resources', 'content-server')
fname = os.path.join(rapydscript_dir, 'srv.pyj')
- with lopen(fname, 'rb') as f:
+ with open(fname, 'rb') as f:
js = set_data(
compile_fast(f.read(), fname),
__RENDER_VERSION__=rv,
__MATHJAX_VERSION__=mathjax_version
).encode('utf-8')
- with lopen(os.path.join(base, 'index.html'), 'rb') as f:
+ with open(os.path.join(base, 'index.html'), 'rb') as f:
html = f.read().replace(b'RESET_STYLES', reset, 1).replace(b'ICONS', icons, 1).replace(b'MAIN_JS', js, 1)
atomic_write(base, 'index-generated.html', html)
diff --git a/src/calibre/utils/tdir_in_cache.py b/src/calibre/utils/tdir_in_cache.py
index b65c0292f0..9672c36449 100644
--- a/src/calibre/utils/tdir_in_cache.py
+++ b/src/calibre/utils/tdir_in_cache.py
@@ -40,7 +40,7 @@ else:
def lock_tdir(path):
lf = os.path.join(path, TDIR_LOCK)
- f = lopen(lf, 'w')
+ f = open(lf, 'w')
eintr_retry_call(fcntl.lockf, f.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
return f
@@ -55,7 +55,7 @@ else:
def is_tdir_locked(path):
lf = os.path.join(path, TDIR_LOCK)
- f = lopen(lf, 'w')
+ f = open(lf, 'w')
try:
eintr_retry_call(fcntl.lockf, f.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
eintr_retry_call(fcntl.lockf, f.fileno(), fcntl.LOCK_UN)
diff --git a/src/calibre/web/feeds/news.py b/src/calibre/web/feeds/news.py
index 35cab8ae43..9d71aa8393 100644
--- a/src/calibre/web/feeds/news.py
+++ b/src/calibre/web/feeds/news.py
@@ -727,7 +727,7 @@ class BasicNewsRecipe(Recipe):
_raw = xml_to_unicode(_raw, strip_encoding_pats=True, resolve_entities=True)[0]
_raw = clean_xml_chars(_raw)
if save_raw:
- with lopen(save_raw, 'wb') as f:
+ with open(save_raw, 'wb') as f:
f.write(_raw.encode('utf-8'))
if as_tree:
from html5_parser import parse
diff --git a/src/calibre/web/fetch/utils.py b/src/calibre/web/fetch/utils.py
index 58eb41599c..4dab35c2ad 100644
--- a/src/calibre/web/fetch/utils.py
+++ b/src/calibre/web/fetch/utils.py
@@ -39,10 +39,10 @@ def rescale_image(data, scale_news_images, compress_news_images_max_size, compre
def prepare_masthead_image(path_to_image, out_path, mi_width, mi_height):
- with lopen(path_to_image, 'rb') as f:
+ with open(path_to_image, 'rb') as f:
img = image_from_data(f.read())
img = blend_on_canvas(img, mi_width, mi_height)
- with lopen(out_path, 'wb') as f:
+ with open(out_path, 'wb') as f:
f.write(image_to_data(img))