Remove redundant io imports

This commit is contained in:
Nick Hall
2015-10-05 19:20:08 +01:00
parent 41c17c3190
commit a86890002f
17 changed files with 28 additions and 46 deletions

View File

@ -33,7 +33,6 @@ creating, and deleting of databases.
import os import os
import sys import sys
import time import time
import io
from urllib.parse import urlparse from urllib.parse import urlparse
from urllib.request import urlopen, url2pathname from urllib.request import urlopen, url2pathname
import tempfile import tempfile
@ -200,7 +199,7 @@ class CLIDbManager(object):
dirpath = os.path.join(dbdir, dpath) dirpath = os.path.join(dbdir, dpath)
path_name = os.path.join(dirpath, NAME_FILE) path_name = os.path.join(dirpath, NAME_FILE)
if os.path.isfile(path_name): if os.path.isfile(path_name):
file = io.open(path_name, 'r', encoding='utf8') file = open(path_name, 'r', encoding='utf8')
name = file.readline().strip() name = file.readline().strip()
file.close() file.close()
@ -259,7 +258,7 @@ class CLIDbManager(object):
name_list = [ name[0] for name in self.current_names ] name_list = [ name[0] for name in self.current_names ]
title = find_next_db_name(name_list) title = find_next_db_name(name_list)
name_file = io.open(path_name, "w", encoding='utf8') name_file = open(path_name, "w", encoding='utf8')
name_file.write(title) name_file.write(title)
name_file.close() name_file.close()
@ -372,10 +371,10 @@ class CLIDbManager(object):
try: try:
filepath = conv_to_unicode(filepath, 'utf8') filepath = conv_to_unicode(filepath, 'utf8')
new_text = conv_to_unicode(new_text, 'utf8') new_text = conv_to_unicode(new_text, 'utf8')
name_file = io.open(filepath, "r", encoding='utf8') name_file = open(filepath, "r", encoding='utf8')
old_text=name_file.read() old_text=name_file.read()
name_file.close() name_file.close()
name_file = io.open(filepath, "w", encoding='utf8') name_file = open(filepath, "w", encoding='utf8')
name_file.write(new_text) name_file.write(new_text)
name_file.close() name_file.close()
except (OSError, IOError) as msg: except (OSError, IOError) as msg:
@ -477,7 +476,7 @@ def find_locker_name(dirpath):
""" """
try: try:
fname = os.path.join(dirpath, "lock") fname = os.path.join(dirpath, "lock")
ifile = io.open(fname, 'r', encoding='utf8') ifile = open(fname, 'r', encoding='utf8')
username = ifile.read().strip() username = ifile.read().strip()
# feature request 2356: avoid genitive form # feature request 2356: avoid genitive form
last = _("Locked by %s") % username last = _("Locked by %s") % username

View File

@ -24,7 +24,6 @@ import sys
import os import os
import unittest import unittest
import re import re
import io
import subprocess import subprocess
from gramps.gen.const import TEMP_DIR from gramps.gen.const import TEMP_DIR
@ -55,7 +54,7 @@ class Test(unittest.TestCase):
@classmethod @classmethod
def setUpClass(cls): def setUpClass(cls):
if not os.path.exists(min1r): if not os.path.exists(min1r):
with io.open(min1r, "w") as f: with open(min1r, "w") as f:
f.write(test_ged) f.write(test_ged)
@classmethod @classmethod
@ -86,7 +85,7 @@ class Test(unittest.TestCase):
"executed CLI command %r" % gcmd) "executed CLI command %r" % gcmd)
# simple validation o output # simple validation o output
self.assertTrue(os.path.isfile(ofile), "output file created") self.assertTrue(os.path.isfile(ofile), "output file created")
with io.open(ofile) as f: with open(ofile) as f:
content = f.read() content = f.read()
g = re.search("INDI", content) g = re.search("INDI", content)
self.assertTrue(g, "found 'INDI' in output file") self.assertTrue(g, "found 'INDI' in output file")
@ -102,7 +101,7 @@ class Test(unittest.TestCase):
pass pass
bogofiles = [os.path.join(ddir, fn) for fn in ("family.db", "lock")] bogofiles = [os.path.join(ddir, fn) for fn in ("family.db", "lock")]
for fn in bogofiles: for fn in bogofiles:
with io.open(fn, "w") as f: with open(fn, "w") as f:
f.write("garbage") f.write("garbage")
# ~same as test 2 # ~same as test 2

View File

@ -24,7 +24,6 @@ Provide the database state class
""" """
import sys import sys
import os import os
import io
from .db import DbReadBase from .db import DbReadBase
from .proxy.proxybase import ProxyDbBase from .proxy.proxybase import ProxyDbBase
@ -190,7 +189,7 @@ class DbState(Callback):
dirpath = os.path.join(dbdir, dpath) dirpath = os.path.join(dbdir, dpath)
path_name = os.path.join(dirpath, "name.txt") path_name = os.path.join(dirpath, "name.txt")
if os.path.isfile(path_name): if os.path.isfile(path_name):
file = io.open(path_name, 'r', encoding='utf8') file = open(path_name, 'r', encoding='utf8')
name = file.readline().strip() name = file.readline().strip()
file.close() file.close()
if dbname == name: if dbname == name:
@ -199,14 +198,14 @@ class DbState(Callback):
backend = None backend = None
fname = os.path.join(dirpath, "database.txt") fname = os.path.join(dirpath, "database.txt")
if os.path.isfile(fname): if os.path.isfile(fname):
ifile = io.open(fname, 'r', encoding='utf8') ifile = open(fname, 'r', encoding='utf8')
backend = ifile.read().strip() backend = ifile.read().strip()
ifile.close() ifile.close()
else: else:
backend = "bsddb" backend = "bsddb"
try: try:
fname = os.path.join(dirpath, "lock") fname = os.path.join(dirpath, "lock")
ifile = io.open(fname, 'r', encoding='utf8') ifile = open(fname, 'r', encoding='utf8')
locked_by = ifile.read().strip() locked_by = ifile.read().strip()
locked = True locked = True
ifile.close() ifile.close()

View File

@ -27,7 +27,6 @@ from xml.sax import make_parser, SAXParseException
import os import os
import sys import sys
import collections import collections
import io
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
# #
@ -104,7 +103,7 @@ class FilterList(object):
if os.path.isfile(self.file): if os.path.isfile(self.file):
parser = make_parser() parser = make_parser()
parser.setContentHandler(FilterParser(self)) parser.setContentHandler(FilterParser(self))
the_file = io.open(self.file, 'r', encoding='utf8') the_file = open(self.file, 'r', encoding='utf8')
parser.parse(the_file) parser.parse(the_file)
the_file.close() the_file.close()
except (IOError, OSError): except (IOError, OSError):
@ -121,7 +120,7 @@ class FilterList(object):
return l.replace('"', '"') return l.replace('"', '"')
def save(self): def save(self):
f = io.open(self.file, 'w', encoding='utf8') f = open(self.file, 'w', encoding='utf8')
f.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n") f.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n")
f.write('<filters>\n') f.write('<filters>\n')
for namespace in self.filter_namespaces: for namespace in self.filter_namespaces:

View File

@ -33,7 +33,6 @@ import os
import sys import sys
import re import re
import traceback import traceback
import io
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
# #
@ -1131,7 +1130,7 @@ class PluginRegister(object):
lenpd = len(self.__plugindata) lenpd = len(self.__plugindata)
full_filename = os.path.join(dir, filename) full_filename = os.path.join(dir, filename)
try: try:
fd = io.open(full_filename, "r", encoding='utf-8') fd = open(full_filename, "r", encoding='utf-8')
except Exception as msg: except Exception as msg:
print(_('ERROR: Failed reading plugin registration %(filename)s') % \ print(_('ERROR: Failed reading plugin registration %(filename)s') % \
{'filename' : filename}) {'filename' : filename})

View File

@ -28,7 +28,6 @@
#------------------------------------------------------------------------ #------------------------------------------------------------------------
from ...const import GRAMPS_LOCALE as glocale from ...const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext _ = glocale.translation.gettext
import io
#------------------------------------------------------------------------ #------------------------------------------------------------------------
# #
@ -143,7 +142,7 @@ class DocBackend(object):
% self.filename) % self.filename)
self._checkfilename() self._checkfilename()
try: try:
self.__file = io.open(self.filename, "w", encoding="utf-8") self.__file = open(self.filename, "w", encoding="utf-8")
except IOError as msg: except IOError as msg:
errmsg = "%s\n%s" % (_("Could not create %s") % self.filename, msg) errmsg = "%s\n%s" % (_("Could not create %s") % self.filename, msg)
raise DocBackendError(errmsg) raise DocBackendError(errmsg)

View File

@ -32,7 +32,7 @@ Report option handling, including saving and parsing.
# Standard Python modules # Standard Python modules
# #
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
import os, io import os
import copy import copy
from xml.sax.saxutils import escape from xml.sax.saxutils import escape
@ -504,7 +504,7 @@ class OptionListCollection(_options.OptionListCollection):
if os.path.isfile(self.filename): if os.path.isfile(self.filename):
p = make_parser() p = make_parser()
p.setContentHandler(OptionParser(self)) p.setContentHandler(OptionParser(self))
the_file = io.open(self.filename, encoding="utf-8") the_file = open(self.filename, encoding="utf-8")
p.parse(the_file) p.parse(the_file)
the_file.close() the_file.close()
except (IOError, OSError, SAXParseException): except (IOError, OSError, SAXParseException):
@ -1000,7 +1000,7 @@ class DocOptionListCollection(_options.OptionListCollection):
if os.path.isfile(self.filename): if os.path.isfile(self.filename):
p = make_parser() p = make_parser()
p.setContentHandler(DocOptionParser(self)) p.setContentHandler(DocOptionParser(self))
the_file = io.open(self.filename, encoding="utf-8") the_file = open(self.filename, encoding="utf-8")
p.parse(the_file) p.parse(the_file)
the_file.close() the_file.close()
except (IOError, OSError, SAXParseException): except (IOError, OSError, SAXParseException):

View File

@ -36,7 +36,6 @@ import configparser
import errno import errno
import copy import copy
import logging import logging
import io
from ..const import GRAMPS_LOCALE as glocale from ..const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext _ = glocale.translation.gettext
@ -334,7 +333,7 @@ class ConfigManager(object):
if exp.errno != errno.EEXIST: if exp.errno != errno.EEXIST:
raise raise
try: try:
key_file = io.open(filename, "w", encoding="utf-8") key_file = open(filename, "w", encoding="utf-8")
except IOError as err: except IOError as err:
logging.warn("Failed to open %s because %s", logging.warn("Failed to open %s because %s",
filename, str(err)) filename, str(err))

View File

@ -32,7 +32,6 @@ File and folder related utility functions
import os import os
import sys import sys
import shutil import shutil
import io
import hashlib import hashlib
import logging import logging
LOG = logging.getLogger(".gen.utils.file") LOG = logging.getLogger(".gen.utils.file")
@ -228,7 +227,7 @@ def create_checksum(full_path):
""" """
full_path = os.path.normpath(full_path) full_path = os.path.normpath(full_path)
try: try:
with io.open(full_path, 'rb') as media_file: with open(full_path, 'rb') as media_file:
md5sum = hashlib.md5(media_file.read()).hexdigest() md5sum = hashlib.md5(media_file.read()).hexdigest()
except IOError: except IOError:
md5sum = '' md5sum = ''

View File

@ -18,7 +18,6 @@
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# #
import sys import sys
import io
import os import os
import logging import logging
LOG = logging.getLogger("ResourcePath") LOG = logging.getLogger("ResourcePath")
@ -61,7 +60,7 @@ class ResourcePath(object):
resource_path = tmp_path resource_path = tmp_path
elif installed: elif installed:
try: try:
with io.open(resource_file, encoding='utf-8', with open(resource_file, encoding='utf-8',
errors='strict') as fp: errors='strict') as fp:
resource_path = conv_to_unicode(fp.readline()) resource_path = conv_to_unicode(fp.readline())
except UnicodeError as err: except UnicodeError as err:

View File

@ -27,7 +27,6 @@
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
import os import os
import sys import sys
import io
##import logging ##import logging
##_LOG = logging.getLogger(".GrampsAboutDialog") ##_LOG = logging.getLogger(".GrampsAboutDialog")
@ -215,7 +214,7 @@ def _get_authors():
parser = make_parser() parser = make_parser()
parser.setContentHandler(AuthorParser(authors, contributors)) parser.setContentHandler(AuthorParser(authors, contributors))
authors_file = io.open(AUTHORS_FILE, encoding='utf-8') authors_file = open(AUTHORS_FILE, encoding='utf-8')
parser.parse(authors_file) parser.parse(authors_file)
authors_file.close() authors_file.close()

View File

@ -42,7 +42,6 @@ _ = glocale.translation.gettext
import time import time
import os import os
import configparser import configparser
import io
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
# #
@ -198,7 +197,7 @@ class GrampletBar(Gtk.Notebook):
""" """
filename = self.configfile filename = self.configfile
try: try:
fp = io.open(filename, "w", encoding='utf-8') fp = open(filename, "w", encoding='utf-8')
except IOError: except IOError:
LOG.warning("Failed writing '%s'; gramplets not saved" % filename) LOG.warning("Failed writing '%s'; gramplets not saved" % filename)
return return

View File

@ -33,7 +33,6 @@ from gi.repository import Gtk
from gi.repository import Pango from gi.repository import Pango
import time import time
import os import os
import io
import configparser import configparser
import logging import logging
@ -1184,7 +1183,7 @@ class GrampletPane(Gtk.ScrolledWindow):
return # something is the matter return # something is the matter
filename = self.configfile filename = self.configfile
try: try:
fp = io.open(filename, "w", encoding='utf-8') fp = open(filename, "w", encoding='utf-8')
except IOError as err: except IOError as err:
LOG.warn("Failed to open %s because $s; gramplets not saved", LOG.warn("Failed to open %s because $s; gramplets not saved",
filename, str(err)) filename, str(err))

View File

@ -35,7 +35,6 @@ import pickle
import os import os
import time import time
import bisect import bisect
import io
from functools import wraps from functools import wraps
import logging import logging
from sys import maxsize, getfilesystemencoding, version_info from sys import maxsize, getfilesystemencoding, version_info
@ -2613,7 +2612,7 @@ def clear_lock_file(name):
def write_lock_file(name): def write_lock_file(name):
if not os.path.isdir(name): if not os.path.isdir(name):
os.mkdir(name) os.mkdir(name)
f = io.open(os.path.join(name, DBLOCKFN), "w", encoding='utf8') f = open(os.path.join(name, DBLOCKFN), "w", encoding='utf8')
if win(): if win():
user = get_env_var('USERNAME') user = get_env_var('USERNAME')
host = get_env_var('USERDOMAIN') host = get_env_var('USERDOMAIN')

View File

@ -28,7 +28,6 @@
# python modules # python modules
# #
#------------------------------------------------------------------------ #------------------------------------------------------------------------
import io
import sys import sys
#------------------------------------------------------------------------ #------------------------------------------------------------------------
@ -156,8 +155,7 @@ class AsciiDoc(BaseDoc, TextDoc):
self.filename = filename self.filename = filename
try: try:
self.f = io.open(self.filename,"w", self.f = open(self.filename, "w", errors = 'backslashreplace')
errors = 'backslashreplace')
except Exception as msg: except Exception as msg:
errmsg = "%s\n%s" % (_("Could not create %s") % self.filename, msg) errmsg = "%s\n%s" % (_("Could not create %s") % self.filename, msg)
raise ReportError(errmsg) raise ReportError(errmsg)

View File

@ -34,7 +34,6 @@
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
import os import os
import time import time
import io
#------------------------------------------------------------------------- #-------------------------------------------------------------------------
# #
@ -239,7 +238,7 @@ class GedcomWriter(UpdateCallback):
""" """
self.dirname = os.path.dirname (filename) self.dirname = os.path.dirname (filename)
self.gedcom_file = io.open(filename, "w", encoding='utf-8') self.gedcom_file = open(filename, "w", encoding='utf-8')
self._header(filename) self._header(filename)
self._submitter() self._submitter()
self._individuals() self._individuals()

View File

@ -468,10 +468,8 @@ class PG30_Def:
raise ProgenError(_("Cannot find DEF file: %(deffname)s") % locals()) raise ProgenError(_("Cannot find DEF file: %(deffname)s") % locals())
# This can throw a IOError # This can throw a IOError
import io
lines = None lines = None
with io.open(fname, buffering=1, with open(fname, buffering=1, encoding='cp437', errors='strict') as f:
encoding='cp437', errors='strict') as f:
lines = f.readlines() lines = f.readlines()
lines = [l.strip() for l in lines] lines = [l.strip() for l in lines]
content = '\n'.join(lines).encode('utf-8') content = '\n'.join(lines).encode('utf-8')