Get rid of lopen()

This commit is contained in:
Kovid Goyal 2023-01-09 19:59:05 +05:30
parent 474de99ec2
commit 4e4928be1a
No known key found for this signature in database
GPG Key ID: 06BC317B515ACE7C
122 changed files with 325 additions and 327 deletions

View File

@ -573,7 +573,7 @@ class GoComics(BasicNewsRecipe):
fname = ascii_filename('%03d_%s' % (num, title)).replace(' ', '_')
path = os.path.join(self.gocomics_dir, fname)
html = '<html><body>{h1}<h2>{date}</h2><div>{img}</div></body></html>'.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, '/')}

View File

@ -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)

View File

@ -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):

View File

@ -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)

View File

@ -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

View File

@ -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)

View File

@ -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'))

View File

@ -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)

View File

@ -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()))

View File

@ -119,7 +119,7 @@ def read_credentials(opts):
from getpass import getpass
pw = getpass(_('Enter the password: '))
elif pw.startswith('<f:') and pw.endswith('>'):
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

View File

@ -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:

View File

@ -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:

View File

@ -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)

View File

@ -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()

View File

@ -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)

View File

@ -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)

View File

@ -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'

View File

@ -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]

View File

@ -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:

View File

@ -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:

View File

@ -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:

View File

@ -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)
'''

View File

@ -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)

View File

@ -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

View File

@ -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)

View File

@ -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'''<?xml version="1.0" encoding="UTF-8"?>
<cache xmlns="http://www.kinoma.com/FskCache/1">
</cache>
@ -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)

View File

@ -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"<?xml version='1.0' encoding='UTF-8'?>",
b'<?xml version="1.0" encoding="UTF-8"?>')
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"<?xml version='1.0' encoding='UTF-8'?>",
b'<?xml version="1.0" encoding="UTF-8"?>')
with lopen(path, 'wb') as f:
with open(path, 'wb') as f:
f.write(raw)
fsync(f)

View File

@ -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)

View File

@ -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):

View File

@ -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,

View File

@ -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)

View File

@ -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

View File

@ -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

View File

@ -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):

View File

@ -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)
# }}}

View File

@ -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)

View File

@ -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

View File

@ -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):

View File

@ -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)

View File

@ -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

View File

@ -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:

View File

@ -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

View File

@ -52,7 +52,7 @@ class OEBOutput(OutputFormatPlugin):
# Needed as I can't get lxml to output opf:role and
# not output <opf:metadata> 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)

View File

@ -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

View File

@ -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'<spine', b'<spine toc="%s"' % as_bytes(ncxid))
f.seek(0)
f.write(raw)

View File

@ -26,14 +26,14 @@ class PMLInput(InputFormatPlugin):
hclose = False
if not hasattr(pml_path, 'read'):
pml_stream = lopen(pml_path, 'rb')
pml_stream = open(pml_path, 'rb')
pclose = True
else:
pml_stream = pml_path
pml_stream.seek(0)
if not hasattr(html_path, 'write'):
html_stream = lopen(html_path, 'wb')
html_stream = open(html_path, 'wb')
hclose = True
else:
html_stream = html_path
@ -134,8 +134,8 @@ class PMLInput(InputFormatPlugin):
opf.create_manifest(manifest_items)
opf.create_spine(pages)
opf.set_toc(toc)
with lopen('metadata.opf', 'wb') as opffile:
with lopen('toc.ncx', 'wb') as tocfile:
with open('metadata.opf', 'wb') as opffile:
with open('toc.ncx', 'wb') as tocfile:
opf.render(opffile, tocfile, 'toc.ncx')
return os.path.join(os.getcwd(), 'metadata.opf')

View File

@ -39,7 +39,7 @@ class PMLOutput(OutputFormatPlugin):
with TemporaryDirectory('_pmlz_output') as tdir:
pmlmlizer = PMLMLizer(log)
pml = str(pmlmlizer.extract_content(oeb_book, opts))
with lopen(os.path.join(tdir, 'index.pml'), 'wb') as out:
with open(os.path.join(tdir, 'index.pml'), 'wb') as out:
out.write(pml.encode(opts.pml_output_encoding, 'replace'))
img_path = os.path.join(tdir, 'index_img')
@ -69,5 +69,5 @@ class PMLOutput(OutputFormatPlugin):
path = os.path.join(out_dir, image_hrefs[item.href])
with lopen(path, 'wb') as out:
with open(path, 'wb') as out:
out.write(data)

View File

@ -27,7 +27,7 @@ class RBOutput(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

View File

@ -64,7 +64,7 @@ class RecipeInput(InputFormatPlugin):
zf = ZipFile(recipe_or_file, 'r')
zf.extractall()
zf.close()
with lopen('download.recipe', 'rb') as f:
with open('download.recipe', 'rb') as f:
self.recipe_source = f.read()
recipe = compile_recipe(self.recipe_source)
recipe.needs_subscription = False
@ -87,7 +87,7 @@ class RecipeInput(InputFormatPlugin):
self.recipe_source = self.recipe_source.encode('utf-8')
recipe = compile_recipe(self.recipe_source)
elif os.access(recipe_or_file, os.R_OK):
with lopen(recipe_or_file, 'rb') as f:
with open(recipe_or_file, 'rb') as f:
self.recipe_source = f.read()
recipe = compile_recipe(self.recipe_source)
log('Using custom recipe')

View File

@ -172,7 +172,7 @@ class RTFInput(InputFormatPlugin):
' Use Microsoft Word or LibreOffice to save this RTF file'
' as HTML and convert that in calibre.')
name = name.replace('.wmf', '.jpg')
with lopen(name, 'wb') as f:
with open(name, 'wb') as f:
f.write(self.default_img)
return name

View File

@ -25,7 +25,7 @@ class RTFOutput(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

View File

@ -241,7 +241,7 @@ class SNBOutput(OutputFormatPlugin):
# img = img.rotate(90)
# x,y = y,x
img = resize_image(img, x // scale, y // scale)
with lopen(imagePath, 'wb') as f:
with open(imagePath, 'wb') as f:
f.write(image_to_data(img, fmt=imagePath.rpartition('.')[-1]))

View File

@ -30,7 +30,7 @@ class TCROutput(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

View File

@ -948,7 +948,7 @@ OptionRecommendation(name='search_replace',
if self.opts.read_metadata_from_opf is not None:
self.opts.read_metadata_from_opf = os.path.abspath(
self.opts.read_metadata_from_opf)
with lopen(self.opts.read_metadata_from_opf, 'rb') as stream:
with open(self.opts.read_metadata_from_opf, 'rb') as stream:
opf = OPF(stream, os.path.dirname(self.opts.read_metadata_from_opf))
mi = opf.to_book_metadata()
self.opts_to_mi(mi)
@ -958,7 +958,7 @@ OptionRecommendation(name='search_replace',
ext = mi.cover.rpartition('.')[-1].lower().strip()
if ext not in ('png', 'jpg', 'jpeg', 'gif'):
ext = 'jpg'
with lopen(mi.cover, 'rb') as stream:
with open(mi.cover, 'rb') as stream:
mi.cover_data = (ext, stream.read())
mi.cover = None
self.user_metadata = mi
@ -1064,7 +1064,7 @@ OptionRecommendation(name='search_replace',
self.opts.debug_pipeline = os.path.abspath(self.opts.debug_pipeline)
if not os.path.exists(self.opts.debug_pipeline):
os.makedirs(self.opts.debug_pipeline)
with lopen(os.path.join(self.opts.debug_pipeline, 'README.txt'), 'wb') as f:
with open(os.path.join(self.opts.debug_pipeline, 'README.txt'), 'wb') as f:
f.write(DEBUG_README)
for x in ('input', 'parsed', 'structure', 'processed'):
x = os.path.join(self.opts.debug_pipeline, x)
@ -1082,7 +1082,7 @@ OptionRecommendation(name='search_replace',
tdir = PersistentTemporaryDirectory('_plumber')
stream = self.input if self.input_fmt == 'recipe' else \
lopen(self.input, 'rb')
open(self.input, 'rb')
if self.input_fmt == 'recipe':
self.opts.original_recipe_input_arg = self.original_input_arg

View File

@ -219,7 +219,7 @@ def cleanup_markup(log, root, styles, dest_dir, detect_cover, XPath):
if os.path.exists(path) and before_count(root, img, limit=10) < 5:
from calibre.utils.imghdr import identify
try:
with lopen(path, 'rb') as imf:
with open(path, 'rb') as imf:
fmt, width, height = identify(imf)
except:
width, height, fmt = 0, 0, None # noqa

View File

@ -376,11 +376,11 @@ class Convert:
def write(self, doc):
toc = create_toc(doc, self.body, self.resolved_link_map, self.styles, self.object_map, self.log, self.namespace)
raw = html.tostring(self.html, encoding='utf-8', doctype='<!DOCTYPE html>')
with lopen(os.path.join(self.dest_dir, 'index.html'), 'wb') as f:
with open(os.path.join(self.dest_dir, 'index.html'), 'wb') as f:
f.write(raw)
css = self.styles.generate_css(self.dest_dir, self.docx, self.notes_nopb, self.nosupsub)
if css:
with lopen(os.path.join(self.dest_dir, 'docx.css'), 'wb') as f:
with open(os.path.join(self.dest_dir, 'docx.css'), 'wb') as f:
f.write(css.encode('utf-8'))
opf = OPFCreator(self.dest_dir, self.mi)
@ -398,7 +398,7 @@ class Convert:
guide.append(E.reference(
href='index.html#' + self.toc_anchor, title=_('Table of Contents'), type='toc'))
toc_file = os.path.join(self.dest_dir, 'toc.ncx')
with lopen(os.path.join(self.dest_dir, 'metadata.opf'), 'wb') as of, open(toc_file, 'wb') as ncx:
with open(os.path.join(self.dest_dir, 'metadata.opf'), 'wb') as of, open(toc_file, 'wb') as ncx:
opf.render(of, ncx, 'toc.ncx', process_guide=process_guide)
if os.path.getsize(toc_file) == 0:
os.remove(toc_file)

View File

@ -23,7 +23,7 @@ def ensure_unicode(obj, enc=preferred_encoding):
def serialize_cover(path):
with lopen(path, 'rb') as f:
with open(path, 'rb') as f:
cd = f.read()
return what(None, cd), cd

View File

@ -171,7 +171,7 @@ class OCFDirReader(OCFReader):
super().__init__()
def open(self, path):
return lopen(os.path.join(self.root, path), 'rb')
return open(os.path.join(self.root, path), 'rb')
def read_bytes(self, path):
with self.open(path) as f:
@ -252,7 +252,7 @@ def set_metadata(stream, mi, apply_null=False, update_timestamp=False, force_ide
raise Exception('no cover')
except Exception:
try:
with lopen(mi.cover, 'rb') as f:
with open(mi.cover, 'rb') as f:
new_cdata = f.read()
except Exception:
pass

View File

@ -47,7 +47,7 @@ def _metadata_from_formats(formats, force_read_metadata=False, pattern=None):
return mi2
for path, ext in zip(formats, extensions):
with lopen(path, 'rb') as stream:
with open(path, 'rb') as stream:
try:
newmi = get_metadata(stream, stream_type=ext,
use_libprs_metadata=True,
@ -232,21 +232,21 @@ def forked_read_metadata(original_path, tdir):
from calibre.ebooks.metadata.worker import run_import_plugins
path = run_import_plugins((original_path,), os.getpid(), tdir)[0]
if path != original_path:
with lopen(os.path.join(tdir, 'file_changed_by_plugins'), 'w') as f:
with open(os.path.join(tdir, 'file_changed_by_plugins'), 'w') as f:
f.write(os.path.abspath(path))
with lopen(path, 'rb') as f:
with open(path, 'rb') as f:
fmt = os.path.splitext(path)[1][1:].lower()
f.seek(0, 2)
sz = f.tell()
with lopen(os.path.join(tdir, 'size.txt'), 'wb') as s:
with open(os.path.join(tdir, 'size.txt'), 'wb') as s:
s.write(str(sz).encode('ascii'))
f.seek(0)
mi = get_metadata(f, fmt)
if mi.cover_data and mi.cover_data[1]:
with lopen(os.path.join(tdir, 'cover.jpg'), 'wb') as f:
with open(os.path.join(tdir, 'cover.jpg'), 'wb') as f:
f.write(mi.cover_data[1])
mi.cover_data = (None, None)
mi.cover = 'cover.jpg'
opf = metadata_to_opf(mi, default_lang='und')
with lopen(os.path.join(tdir, 'metadata.opf'), 'wb') as f:
with open(os.path.join(tdir, 'metadata.opf'), 'wb') as f:
f.write(opf)

View File

@ -227,7 +227,7 @@ class TOC(list):
def read_html_toc(self, toc):
self.base_path = os.path.dirname(toc)
with lopen(toc, 'rb') as f:
with open(toc, 'rb') as f:
parsed_toc = parse_html_toc(f.read())
for href, fragment, txt in parsed_toc:
add = True

View File

@ -303,7 +303,7 @@ class MobiReader:
def write_as_utf8(path, data):
if isinstance(data, str):
data = data.encode('utf-8')
with lopen(path, 'wb') as f:
with open(path, 'wb') as f:
f.write(data)
parse_cache[htmlfile] = root
@ -311,7 +311,7 @@ class MobiReader:
ncx = io.BytesIO()
opf, ncx_manifest_entry = self.create_opf(htmlfile, guide, root)
self.created_opf_path = os.path.splitext(htmlfile)[0] + '.opf'
opf.render(lopen(self.created_opf_path, 'wb'), ncx,
opf.render(open(self.created_opf_path, 'wb'), ncx,
ncx_manifest_entry=ncx_manifest_entry)
ncx = ncx.getvalue()
if ncx:

View File

@ -70,7 +70,7 @@ class Resources:
try:
from calibre.utils.img import optimize_png
optimize_png(pt.name)
data = lopen(pt.name, 'rb').read()
data = open(pt.name, 'rb').read()
finally:
os.remove(pt.name)
return func(data)

View File

@ -579,7 +579,7 @@ class DirContainer:
if path is None:
path = self.opfname
path = os.path.join(self.rootdir, self._unquote(path))
with lopen(path, 'rb') as f:
with open(path, 'rb') as f:
return f.read()
def write(self, path, data):
@ -587,7 +587,7 @@ class DirContainer:
dir = os.path.dirname(path)
if not os.path.isdir(dir):
os.makedirs(dir)
with lopen(path, 'wb') as f:
with open(path, 'wb') as f:
return f.write(data)
def exists(self, path):

View File

@ -50,7 +50,7 @@ class SpineItem(str):
if not os.path.exists(path) and os.path.exists(ppath):
path = ppath
obj = super().__new__(cls, path)
with lopen(path, 'rb') as f:
with open(path, 'rb') as f:
raw = f.read()
if from_epub:
# According to the spec, HTML in EPUB must be encoded in utf-8 or

View File

@ -372,7 +372,7 @@ class Container(ContainerBase): # {{{
base = os.path.dirname(path)
if not os.path.exists(base):
os.makedirs(base)
with lopen(path, 'wb') as f:
with open(path, 'wb') as f:
if hasattr(data, 'read'):
shutil.copyfileobj(data, f)
else:
@ -587,7 +587,7 @@ class Container(ContainerBase): # {{{
return set()
def parse(self, path, mime):
with lopen(path, 'rb') as src:
with open(path, 'rb') as src:
data = src.read()
if mime in OEB_DOCS:
data = self.parse_xhtml(data, self.relpath(path))
@ -968,7 +968,7 @@ class Container(ContainerBase): # {{{
base = os.path.dirname(path)
if not os.path.exists(base):
os.makedirs(base)
lopen(path, 'wb').close()
open(path, 'wb').close()
return item
def format_opf(self):
@ -1023,7 +1023,7 @@ class Container(ContainerBase): # {{{
if self.cloned and nlinks_file(dest) > 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.'))

View File

@ -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")

View File

@ -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:

View File

@ -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))

View File

@ -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')])

View File

@ -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]

View File

@ -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:

View File

@ -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('<head', '<!-- created by calibre\'s pdftohtml -->\n <head', 1)
@ -150,7 +150,7 @@ def parse_outline(raw, output_dir):
def flip_image(img, flip):
from calibre.utils.img import flip_image, image_and_format_from_data, image_to_data
with lopen(img, 'r+b') as f:
with open(img, 'r+b') as f:
img, fmt = image_and_format_from_data(f.read())
img = flip_image(img, horizontal='x' in flip, vertical='y' in flip)
f.seek(0), f.truncate()

View File

@ -124,7 +124,7 @@ def explode(ebook_file, output_dir):
# The question was answered with No
return
h = '_' if iswindows else '.'
with lopen(os.path.join(output_dir, h + '__explode_fmt__'), 'wb') as f:
with open(os.path.join(output_dir, h + '__explode_fmt__'), 'wb') as f:
f.write(fmt.encode('utf-8'))
prints('Book extracted to', output_dir)
prints('Make your changes and once you are done, use --implode-book to rebuild')
@ -139,7 +139,7 @@ def implode(output_dir, ebook_file):
h = '_' if iswindows else '.'
efmt_path = os.path.join(output_dir, h + '__explode_fmt__')
try:
with lopen(efmt_path, 'rb') as f:
with open(efmt_path, 'rb') as f:
efmt = f.read().decode('utf-8')
except Exception:
raise SystemExit('The folder %s does not seem to have been created by --explode-book' % output_dir)

View File

@ -227,7 +227,7 @@ def opf_writer(path, opf_name, manifest, spine, mi):
opf = OPFCreator(path, mi)
opf.create_manifest(manifest)
opf.create_spine(spine)
with lopen(os.path.join(path, opf_name), 'wb') as opffile:
with open(os.path.join(path, opf_name), 'wb') as opffile:
opf.render(opffile)

View File

@ -127,7 +127,7 @@ class AddAction(InterfaceAction):
_('Are you sure you want to set the same'
' cover for all %d books?')%len(ids)):
return
with lopen(images[0], 'rb') as f:
with open(images[0], 'rb') as f:
cdata = f.read()
self.gui.current_db.new_api.set_cover({book_id: cdata for book_id in ids})
self.gui.refresh_cover_browser()

View File

@ -671,7 +671,7 @@ class EditMetadataAction(InterfaceAction):
for src_book in src_books:
if src_book:
fmt = os.path.splitext(src_book)[-1].replace('.', '').upper()
with lopen(src_book, 'rb') as f:
with open(src_book, 'rb') as f:
self.gui.library_view.model().db.add_format(dest_id, fmt, f, index_is_id=True,
notify=False, replace=replace)

View File

@ -668,7 +668,7 @@ class EditorWidget(QTextEdit, LineEditECM): # {{{
path = files[0]
d.url.setText(path)
if path and os.path.exists(path):
with lopen(path, 'rb') as f:
with open(path, 'rb') as f:
q = what(f)
is_image = q in {'jpeg', 'png', 'gif'}
d.treat_as_image.setChecked(is_image)
@ -776,7 +776,7 @@ class EditorWidget(QTextEdit, LineEditECM): # {{{
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'}:

View File

@ -601,7 +601,7 @@ class DeviceManager(Thread): # {{{
if DEBUG:
prints('Setting metadata in:', mi.title, 'at:',
f, file=sys.__stdout__)
with lopen(f, 'r+b') as stream:
with open(f, 'r+b') as stream:
if cpb:
newmi = mi.deepcopy_metadata()
newmi.template_to_attribute(mi, cpb)
@ -658,7 +658,7 @@ class DeviceManager(Thread): # {{{
name = sanitize_file_name(os.path.basename(path))
dest = os.path.join(target, name)
if os.path.abspath(dest) != os.path.abspath(path):
with lopen(dest, 'wb') as f:
with open(dest, 'wb') as f:
self.device.get_file(path, f)
def save_books(self, done, paths, target, add_as_step_to_job=None):
@ -667,7 +667,7 @@ class DeviceManager(Thread): # {{{
to_job=add_as_step_to_job)
def _view_book(self, path, target):
with lopen(target, 'wb') as f:
with open(target, 'wb') as f:
self.device.get_file(path, f)
return target
@ -1779,7 +1779,7 @@ class DeviceMixin: # {{{
def update_thumbnail(self, book):
if book.cover and os.access(book.cover, os.R_OK):
with lopen(book.cover, 'rb') as f:
with open(book.cover, 'rb') as f:
book.thumbnail = self.cover_to_thumbnail(f.read())
else:
cprefs = self.default_thumbnail_prefs

View File

@ -115,7 +115,7 @@ class Sendmail:
from_ = opts.from_
if not from_:
from_ = 'calibre <calibre@'+socket.getfqdn()+'>'
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 = []

View File

@ -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:

View File

@ -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):

View File

@ -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)

View File

@ -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()

View File

@ -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

View File

@ -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()

View File

@ -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 = '''\
<!DOCTYPE html>

View File

@ -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/'):

View File

@ -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)

View File

@ -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):

View File

@ -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:

View File

@ -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:

View File

@ -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)

View File

@ -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():

View File

@ -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'}:

View File

@ -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)

View File

@ -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)

View File

@ -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)

View File

@ -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

View File

@ -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())

View File

@ -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'])

Some files were not shown because too many files have changed in this diff Show More