diff --git a/anki/importing/anki2.py b/anki/importing/anki2.py index d938f0ff4..dfd4f1a0d 100644 --- a/anki/importing/anki2.py +++ b/anki/importing/anki2.py @@ -340,7 +340,8 @@ insert or ignore into revlog values (?,?,?,?,?,?,?,?,?)""", revlog) dir = self.src.media.dir() path = os.path.join(dir, fname) try: - return open(path, "rb").read() + with open(path, "rb") as f: + return f.read() except (IOError, OSError): return @@ -356,7 +357,8 @@ insert or ignore into revlog values (?,?,?,?,?,?,?,?,?)""", revlog) path = os.path.join(self.dst.media.dir(), unicodedata.normalize("NFC", fname)) try: - open(path, "wb").write(data) + with open(path, "wb") as f: + f.write(data) except (OSError, IOError): # the user likely used subdirectories pass diff --git a/anki/importing/apkg.py b/anki/importing/apkg.py index a91753f17..e31bc4b07 100644 --- a/anki/importing/apkg.py +++ b/anki/importing/apkg.py @@ -14,7 +14,8 @@ class AnkiPackageImporter(Anki2Importer): self.zip = z = zipfile.ZipFile(self.file) col = z.read("collection.anki2") colpath = tmpfile(suffix=".anki2") - open(colpath, "wb").write(col) + with open(colpath, "wb") as f: + f.write(col) self.file = colpath # we need the media dict in advance, and we'll need a map of fname -> # number to use during the import @@ -34,7 +35,8 @@ class AnkiPackageImporter(Anki2Importer): continue path = os.path.join(self.col.media.dir(), file) if not os.path.exists(path): - open(path, "wb").write(z.read(c)) + with open(path, "wb") as f: + f.write(z.read(c)) def _srcMediaData(self, fname): if fname in self.nameToNum: diff --git a/anki/latex.py b/anki/latex.py index 75b9046b6..dc7408c73 100644 --- a/anki/latex.py +++ b/anki/latex.py @@ -127,12 +127,14 @@ package in the LaTeX header instead.""") % bad return finally: os.chdir(oldcwd) + log.close() def _errMsg(type, texpath): msg = (_("Error executing %s.") % type) + "
" msg += (_("Generated file: %s") % texpath) + "
" try: - log = open(namedtmp("latex_log.txt", rm=False)).read() + with open(namedtmp("latex_log.txt", rm=False)) as f: + log = f.read() if not log: raise Exception() msg += "
" + html.escape(log) + "
" diff --git a/anki/media.py b/anki/media.py index 0e53c0478..91b124a1f 100644 --- a/anki/media.py +++ b/anki/media.py @@ -138,7 +138,8 @@ create table meta (dirMod int, lastUsn int); insert into meta values (0, 0); # opath must be in unicode def addFile(self, opath): - return self.writeData(opath, open(opath, "rb").read()) + with open(opath, "rb") as f: + return self.writeData(opath, f.read()) def writeData(self, opath, data, typeHint=None): # if fname is a full path, use only the basename @@ -171,11 +172,13 @@ create table meta (dirMod int, lastUsn int); insert into meta values (0, 0); path = os.path.join(self.dir(), fname) # if it doesn't exist, copy it directly if not os.path.exists(path): - open(path, "wb").write(data) + with open(path, "wb") as f: + f.write(data) return fname # if it's identical, reuse - if checksum(open(path, "rb").read()) == csum: - return fname + with open(path, "rb") as f: + if checksum(f.read()) == csum: + return fname # otherwise, increment the index in the filename reg = " \((\d+)\)$" if not re.search(reg, root): @@ -375,7 +378,8 @@ create table meta (dirMod int, lastUsn int); insert into meta values (0, 0); return int(os.stat(path).st_mtime) def _checksum(self, path): - return checksum(open(path, "rb").read()) + with open(path, "rb") as f: + return checksum(f.read()) def _changed(self): "Return dir mtime if it has changed since the last findChanges()" @@ -553,7 +557,8 @@ create table meta (dirMod int, lastUsn int); insert into meta values (0, 0); else: name = unicodedata.normalize("NFC", name) # save file - open(name, "wb").write(data) + with open(name, "wb") as f: + f.write(data) # update db media.append((name, csum, self._mtime(name), 0)) cnt += 1 diff --git a/tests/test_exporting.py b/tests/test_exporting.py index 61c417356..261e27dcc 100644 --- a/tests/test_exporting.py +++ b/tests/test_exporting.py @@ -68,7 +68,8 @@ def test_export_anki(): @nose.with_setup(setup1) def test_export_ankipkg(): # add a test file to the media folder - open(os.path.join(deck.media.dir(), "今日.mp3"), "w").write("test") + with open(os.path.join(deck.media.dir(), "今日.mp3"), "w") as f: + f.write("test") n = deck.newNote() n['Front'] = '[sound:今日.mp3]' deck.addNote(n) diff --git a/tests/test_importing.py b/tests/test_importing.py index 65e418a6e..00c8af53b 100644 --- a/tests/test_importing.py +++ b/tests/test_importing.py @@ -19,7 +19,8 @@ def test_anki2_mediadupes(): mid = n.model()['id'] tmp.addNote(n) # add that sound to media folder - open(os.path.join(tmp.media.dir(), "foo.mp3"), "w").write("foo") + with open(os.path.join(tmp.media.dir(), "foo.mp3"), "w") as f: + f.write("foo") tmp.close() # it should be imported correctly into an empty deck empty = getEmptyCol() @@ -36,7 +37,8 @@ def test_anki2_mediadupes(): # if the local file content is different, and import should trigger a # rename empty.remCards(empty.db.list("select id from cards")) - open(os.path.join(empty.media.dir(), "foo.mp3"), "w").write("bar") + with open(os.path.join(empty.media.dir(), "foo.mp3"), "w") as f: + f.write("bar") imp = Anki2Importer(empty, tmp.path) imp.run() assert sorted(os.listdir(empty.media.dir())) == [ @@ -46,7 +48,8 @@ def test_anki2_mediadupes(): # if the localized media file already exists, we rewrite the note and # media empty.remCards(empty.db.list("select id from cards")) - open(os.path.join(empty.media.dir(), "foo.mp3"), "w").write("bar") + with open(os.path.join(empty.media.dir(), "foo.mp3"), "w") as f: + f.write("bar") imp = Anki2Importer(empty, tmp.path) imp.run() assert sorted(os.listdir(empty.media.dir())) == [ @@ -70,7 +73,8 @@ def test_apkg(): assert os.listdir(tmp.media.dir()) == ['foo.wav'] # but if the local file has different data, it will rename tmp.remCards(tmp.db.list("select id from cards")) - open(os.path.join(tmp.media.dir(), "foo.wav"), "w").write("xyz") + with open(os.path.join(tmp.media.dir(), "foo.wav"), "w") as f: + f.write("xyz") imp = AnkiPackageImporter(tmp, apkg) imp.run() assert len(os.listdir(tmp.media.dir())) == 2 diff --git a/tests/test_media.py b/tests/test_media.py index ca6d19e2b..e8198a543 100644 --- a/tests/test_media.py +++ b/tests/test_media.py @@ -12,13 +12,15 @@ def test_add(): d = getEmptyCol() dir = tempfile.mkdtemp(prefix="anki") path = os.path.join(dir, "foo.jpg") - open(path, "w").write("hello") + with open(path, "w") as f: + f.write("hello") # new file, should preserve name assert d.media.addFile(path) == "foo.jpg" # adding the same file again should not create a duplicate assert d.media.addFile(path) == "foo.jpg" # but if it has a different md5, it should - open(path, "w").write("world") + with open(path, "w") as f: + f.write("world") assert d.media.addFile(path) == "foo (1).jpg" def test_strings(): @@ -61,7 +63,8 @@ def test_deckIntegration(): f['Front'] = "one"; f['Back'] = "" d.addNote(f) # and add another file which isn't used - open(os.path.join(d.media.dir(), "foo.jpg"), "w").write("test") + with open(os.path.join(d.media.dir(), "foo.jpg"), "w") as f: + f.write("test") # check media ret = d.media.check() assert ret[0] == ["fake2.png"] @@ -78,7 +81,8 @@ def test_changes(): # add a file dir = tempfile.mkdtemp(prefix="anki") path = os.path.join(dir, "foo.jpg") - open(path, "w").write("hello") + with open(path, "w") as f: + f.write("hello") time.sleep(1) path = d.media.addFile(path) # should have been logged @@ -87,12 +91,14 @@ def test_changes(): assert not list(removed()) # if we modify it, the cache won't notice time.sleep(1) - open(path, "w").write("world") + with open(path, "w") as f: + f.write("world") assert len(list(added())) == 1 assert not list(removed()) # but if we add another file, it will time.sleep(1) - open(path+"2", "w").write("yo") + with open(path+"2", "w") as f: + f.write("yo") d.media.findChanges() assert len(list(added())) == 2 assert not list(removed()) diff --git a/tests/test_stats.py b/tests/test_stats.py index 712bd4bf4..b7212d1e5 100644 --- a/tests/test_stats.py +++ b/tests/test_stats.py @@ -26,5 +26,6 @@ def test_graphs(): d = aopen(os.path.expanduser("~/test.anki2")) g = d.stats() rep = g.report() - open(os.path.expanduser("~/test.html"), "w").write(rep) + with open(os.path.expanduser("~/test.html"), "w") as f: + f.write(rep) return