Merge pull request #124 from sam-m888/MissedWithOpen

Missed 'open' statements
This commit is contained in:
Doug Blank 2016-04-30 02:56:10 -04:00
commit cec4bd7a15
22 changed files with 336 additions and 364 deletions

View File

@ -265,9 +265,8 @@ class CLIManager(object):
# Attempt to figure out the database title
path = os.path.join(filename, "name.txt")
try:
ifile = open(path)
with open(path) as ifile:
title = ifile.readline().strip()
ifile.close()
except:
title = filename

View File

@ -2027,9 +2027,8 @@ class DbGeneric(DbWriteBase, DbReadBase, UpdateCallback, Callback):
"""
filepath = os.path.join(self._directory, "name.txt")
try:
name_file = open(filepath, "r")
with open(filepath, "r") as name_file:
name = name_file.readline().strip()
name_file.close()
except (OSError, IOError) as msg:
LOG.error(str(msg))
name = None
@ -2131,9 +2130,8 @@ class DbGeneric(DbWriteBase, DbReadBase, UpdateCallback, Callback):
if self._directory:
filepath = os.path.join(self._directory, "bdbversion.txt")
try:
name_file = open(filepath, "r", encoding='utf-8')
with open(filepath, "r", encoding='utf-8') as name_file:
version = name_file.readline().strip()
name_file.close()
except (OSError, IOError) as msg:
self.__log_error()
version = "(0, 0, 0)"

View File

@ -118,7 +118,7 @@ class FilterList(object):
return l.replace('"', '"')
def save(self):
f = open(self.file, 'w', encoding='utf8')
with open(self.file, 'w', encoding='utf8') as f:
f.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n")
f.write('<filters>\n')
for namespace in self.filter_namespaces:
@ -142,4 +142,3 @@ class FilterList(object):
f.write(' </filter>\n')
f.write('</object>\n')
f.write('</filters>\n')
f.close()

View File

@ -1130,14 +1130,13 @@ class PluginRegister(object):
lenpd = len(self.__plugindata)
full_filename = os.path.join(dir, filename)
try:
fd = open(full_filename, "r", encoding='utf-8')
with open(full_filename, "r", encoding='utf-8') as fd:
stream = fd.read()
except Exception as msg:
print(_('ERROR: Failed reading plugin registration %(filename)s') % \
{'filename' : filename})
print(msg)
continue
stream = fd.read()
fd.close()
if os.path.exists(os.path.join(os.path.dirname(full_filename),
'locale')):
try:

View File

@ -527,9 +527,8 @@ class BookList(object):
try:
p = make_parser()
p.setContentHandler(BookParser(self, self.dbase))
the_file = open(self.file)
with open(self.file) as the_file:
p.parse(the_file)
the_file.close()
except (IOError, OSError, ValueError, SAXParseException, KeyError,
AttributeError):
pass

View File

@ -83,9 +83,8 @@ class PageSizeParser(handler.ContentHandler):
try:
parser = make_parser()
parser.setContentHandler(PageSizeParser(paper_sizes))
the_file = open(PAPERSIZE)
with open(PAPERSIZE) as the_file:
parser.parse(the_file)
the_file.close()
paper_sizes.append(PaperSize("Custom Size", -1, -1)) # always in English
except (IOError, OSError, SAXParseException):
paper_sizes = [

View File

@ -333,12 +333,7 @@ class ConfigManager(object):
if exp.errno != errno.EEXIST:
raise
try:
key_file = open(filename, "w", encoding="utf-8")
except IOError as err:
logging.warn("Failed to open %s because %s",
filename, str(err))
return;
with open(filename, "w", encoding="utf-8") as key_file:
key_file.write(";; Gramps key file\n")
key_file.write((";; Automatically created at %s" %
time.strftime("%Y/%m/%d %H:%M:%S")) + "\n\n")
@ -360,8 +355,11 @@ class ConfigManager(object):
key,
repr(value)))
key_file.write("\n")
key_file.close()
# else, no filename given; nothing to save so do nothing quietly
except IOError as err:
logging.warn("Failed to open %s because %s",
filename, str(err))
return
def get(self, key):
"""

View File

@ -102,9 +102,8 @@ class GrampsAboutDialog(Gtk.AboutDialog):
self.set_artists(artists.split('\n'))
try:
ifile = open(LICENSE_FILE, "r")
with open(LICENSE_FILE, "r") as ifile:
self.set_license(ifile.read().replace('\x0c', ''))
ifile.close()
except IOError:
self.set_license("License file is missing")
@ -222,9 +221,8 @@ def _get_authors():
parser = make_parser()
parser.setContentHandler(AuthorParser(authors, contributors))
authors_file = open(AUTHORS_FILE, encoding='utf-8')
with open(AUTHORS_FILE, encoding='utf-8') as authors_file:
parser.parse(authors_file)
authors_file.close()
authors_text = [authors, contributors]

View File

@ -691,9 +691,8 @@ class DbManager(CLIDbManager):
node = self.model.get_iter(path)
filename = self.model.get_value(node, FILE_COL)
try:
name_file = open(filename, "r")
with open(filename, "r") as name_file:
file_name_to_delete=name_file.read()
name_file.close()
remove_filename(file_name_to_delete)
directory = self.data_to_delete[1]
for (top, dirs, files) in os.walk(directory):

View File

@ -218,10 +218,7 @@ class GrampletBar(Gtk.Notebook):
"""
filename = self.configfile
try:
fp = open(filename, "w", encoding='utf-8')
except IOError:
LOG.warning("Failed writing '%s'; gramplets not saved" % filename)
return
with open(filename, "w", encoding='utf-8') as fp:
fp.write(";; Gramplet bar configuration file" + NL)
fp.write((";; Automatically created at %s" %
time.strftime("%Y/%m/%d %H:%M:%S")) + NL + NL)
@ -261,7 +258,9 @@ class GrampletBar(Gtk.Notebook):
fp.write(("page=%d" + NL) % page_num)
fp.write(NL)
fp.close()
except IOError:
LOG.warning("Failed writing '%s'; gramplets not saved" % filename)
return
def set_active(self):
"""

View File

@ -1187,11 +1187,7 @@ class GrampletPane(Gtk.ScrolledWindow):
return # something is the matter
filename = self.configfile
try:
fp = open(filename, "w", encoding='utf-8')
except IOError as err:
LOG.warn("Failed to open %s because $s; gramplets not saved",
filename, str(err))
return
with open(filename, "w", encoding='utf-8') as fp:
fp.write(";; Gramps gramplets file\n")
fp.write(";; Automatically created at %s" %
time.strftime("%Y/%m/%d %H:%M:%S\n\n"))
@ -1262,7 +1258,10 @@ class GrampletPane(Gtk.ScrolledWindow):
else:
fp.write("%s=%s\n\n" % (key, base_opts[key]))
fp.close()
except IOError as err:
LOG.warn("Failed to open %s because $s; gramplets not saved",
filename, str(err))
return
def drop_widget(self, source, context, x, y, timedata):
"""

View File

@ -2040,9 +2040,8 @@ class DbBsddbRead(DbReadBase, Callback):
"""
filepath = os.path.join(self.path, "name.txt")
try:
name_file = open(filepath, "r", encoding='utf-8')
with open(filepath, "r", encoding='utf-8') as name_file:
name = name_file.readline().strip()
name_file.close()
except (OSError, IOError) as msg:
self.__log_error()
name = None
@ -2051,9 +2050,8 @@ class DbBsddbRead(DbReadBase, Callback):
def get_version(self):
filepath = os.path.join(self.path, "bdbversion.txt")
try:
name_file = open(filepath, "r", encoding='utf-8')
with open(filepath, "r", encoding='utf-8') as name_file:
version = name_file.readline().strip()
name_file.close()
except (OSError, IOError) as msg:
self.__log_error()
version = "(0, 0, 0)"

View File

@ -16,7 +16,7 @@ def get_dbdir_summary(dirpath, name):
bdbversion_file = os.path.join(dirpath, BDBVERSFN)
if os.path.isfile(bdbversion_file):
vers_file = open(bdbversion_file)
with open(bdbversion_file) as vers_file:
bsddb_version = vers_file.readline().strip()
else:
return "Unknown", "Unknown", "Unknown"

View File

@ -458,8 +458,8 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback):
def __log_error(self):
mypath = os.path.join(self.get_save_path(),DBRECOVFN)
ofile = open(mypath, "w")
ofile.close()
with open(mypath, "w") as ofile:
pass
try:
clear_lock_file(self.get_save_path())
except:
@ -2537,7 +2537,7 @@ class DbBsddb(DbBsddbRead, DbWriteBase, UpdateCallback):
schema_version = self.metadata.get(b'version', default=None)
bdbversion_file = os.path.join(self.path, BDBVERSFN)
if os.path.isfile(bdbversion_file):
vers_file = open(bdbversion_file)
with open(bdbversion_file) as vers_file:
bsddb_version = vers_file.readline().strip()
bsddb_version = ".".join([str(v) for v in safe_eval(bsddb_version)])
else:
@ -2591,7 +2591,7 @@ def do_export(database):
try:
for (base, tbl) in build_tbl_map(database):
backup_name = mk_tmp_name(database, base)
backup_table = open(backup_name, 'wb')
with open(backup_name, 'wb') as backup_table:
cursor = tbl.cursor()
data = cursor.first()
@ -2599,7 +2599,6 @@ def do_export(database):
pickle.dump(data, backup_table, 2)
data = cursor.next()
cursor.close()
backup_table.close()
except (IOError,OSError):
return
@ -2620,7 +2619,7 @@ def do_restore(database):
"""
for (base, tbl) in build_tbl_map(database):
backup_name = mk_backup_name(database, base)
backup_table = open(backup_name, 'rb')
with open(backup_name, 'rb') as backup_table:
load_tbl_txn(database, backup_table, tbl)
database.rebuild_secondary()
@ -2678,7 +2677,7 @@ def clear_lock_file(name):
def write_lock_file(name):
if not os.path.isdir(name):
os.mkdir(name)
f = open(os.path.join(name, DBLOCKFN), "w", encoding='utf8')
with open(os.path.join(name, DBLOCKFN), "w", encoding='utf8') as f:
if win():
user = get_env_var('USERNAME')
host = get_env_var('USERDOMAIN')
@ -2700,7 +2699,6 @@ def write_lock_file(name):
# Save only the username and host, so the massage can be
# printed with correct locale in DbManager.py when a lock is found
f.write(text)
f.close()
def upgrade_researcher(owner_data):
"""

View File

@ -1214,9 +1214,8 @@ class ODFDoc(BaseDoc, TextDoc, DrawDoc):
for image in self.media_list:
try:
ifile = open(image[0], mode='rb')
with open(image[0], mode='rb') as ifile:
self._add_zip(zfile, "Pictures/%s" % image[1], ifile.read(), t)
ifile.close()
except:
errmsg = "%s\n%s" % (_("Could not open %s") % image[0],
msg)

View File

@ -121,7 +121,7 @@ class FtreeWriter(object):
id_map[key] = n
id_name[key] = get_name(pn, sn, count)
f = open(self.filename,"w")
with open(self.filename,"w") as f:
for key in self.plist:
self.update()
@ -174,7 +174,6 @@ class FtreeWriter(object):
f.write('%s;%s;%s;%s;%s;%s\n' % (name, father, mother, email, web,
dates))
f.close()
return True
def fdate(val):

View File

@ -238,7 +238,7 @@ class GedcomWriter(UpdateCallback):
"""
self.dirname = os.path.dirname (filename)
self.gedcom_file = open(filename, "w", encoding='utf-8')
with open(filename, "w", encoding='utf-8') as self.gedcom_file:
self._header(filename)
self._submitter()
self._individuals()
@ -248,7 +248,7 @@ class GedcomWriter(UpdateCallback):
self._notes()
self._writeln(0, "TRLR")
self.gedcom_file.close()
return True
def _writeln(self, level, token, textlines="", limit=72):

View File

@ -90,15 +90,7 @@ class GeneWebWriter(object):
self.dirname = os.path.dirname (self.filename)
try:
self.g = open(self.filename, "wb")
except IOError as msg:
msg2 = _("Could not create %s") % self.filename
self.user.notify_error(msg2, str(msg))
return False
except:
self.user.notify_error(_("Could not create %s") % self.filename)
return False
with open(self.filename, "wb") as self.g:
self.flist = [x for x in self.db.iter_family_handles()]
if len(self.flist) < 1:
self.user.notify_error(_("No families matched by selected filter"))
@ -111,8 +103,14 @@ class GeneWebWriter(object):
self.write_family(key)
self.writeln("")
self.g.close()
return True
except IOError as msg:
msg2 = _("Could not create %s") % self.filename
self.user.notify_error(msg2, str(msg))
return False
except:
self.user.notify_error(_("Could not create %s") % self.filename)
return False
def write_family(self, family_handle):
family = self.db.get_family_from_handle(family_handle)

View File

@ -96,15 +96,7 @@ class CalendarWriter(object):
self.dirname = os.path.dirname (filename)
try:
self.g = open(filename,"w")
except IOError as msg:
msg2 = _("Could not create %s") % filename
self.user.notify_error(msg2, str(msg))
return False
except:
self.user.notify_error(_("Could not create %s") % filename)
return False
with open(filename,"w") as self.g:
self.writeln("BEGIN:VCALENDAR")
self.writeln("PRODID:-//GNU//Gramps//EN")
self.writeln("VERSION:1.0")
@ -122,8 +114,14 @@ class CalendarWriter(object):
self.writeln("")
self.writeln("END:VCALENDAR")
self.g.close()
return True
except IOError as msg:
msg2 = _("Could not create %s") % filename
self.user.notify_error(msg2, str(msg))
return False
except:
self.user.notify_error(_("Could not create %s") % filename)
return False
def write_family(self, family_handle):
family = self.db.get_family_from_handle(family_handle)

View File

@ -67,10 +67,7 @@ def importData(database, filename, user):
database.__class__.__bases__
try:
ifile = open(filename, "rb")
except IOError:
return
with open(filename, "rb") as ifile:
ansel = False
gramps = False
for index in range(50):
@ -87,7 +84,9 @@ def importData(database, filename, user):
ansel = True
if len(line) > 2 and line[1][0:4] == 'SOUR' and line[2] == "GRAMPS":
gramps = True
ifile.close()
except IOError:
return
if not gramps and ansel:
top = Glade()

View File

@ -1127,15 +1127,13 @@ class GedcomInfoDB(object):
self.standard = GedcomDescription("GEDCOM 5.5 standard")
self.standard.set_dest("GEDCOM 5.5")
try:
filepath = os.path.join(DATA_DIR, "gedcom.xml")
ged_file = open(filepath, "rb")
except:
if not os.path.exists(filepath):
return
with open(filepath, "rb") as ged_file:
parser = GedInfoParser(self)
parser.parse(ged_file)
ged_file.close()
def add_description(self, name, obj):
self.map[name] = obj

View File

@ -572,9 +572,8 @@ class VerifyResults(ManagedWindow):
def _save_ignored(self,filename):
try:
f = open(filename,'wb')
with open(filename,'wb') as f:
pickle.dump(self.ignores, f, 1)
f.close()
return True
except IOError:
return False