[python-debian/master 09/36] Use open() rather than file(); file() does not exist in Python 3.

Colin Watson cjwatson at canonical.com
Mon Oct 8 07:41:24 UTC 2012


---
 README.deb822                           |   12 ++++++------
 examples/deb822/depgraph                |    2 +-
 examples/deb822/grep-maintainer         |    2 +-
 examples/deb822/grep_native_packages.py |    2 +-
 examples/debfile/extract_cron           |    2 +-
 examples/debtags/tagminer               |    2 +-
 lib/debian/deb822.py                    |    7 ++++---
 lib/debian/debian_support.py            |    6 +++---
 tests/test_deb822.py                    |   26 +++++++++++++-------------
 9 files changed, 31 insertions(+), 30 deletions(-)

diff --git a/README.deb822 b/README.deb822
index 104ec0f..89e7d64 100644
--- a/README.deb822
+++ b/README.deb822
@@ -47,7 +47,7 @@ Here is a list of the types deb822 knows about:
 Input
 =====
 
-Deb822 objects are normally initialized from a file() object, from which
+Deb822 objects are normally initialized from a file object, from which
 at most one paragraph is read, or a string.
 
 Alternatively, any sequence that returns one line of input at a time may
@@ -63,10 +63,9 @@ All classes provide an "iter_paragraphs" class method to easily go over
 each stanza in a file with multiple entries, like a Packages.gz file.
 For example:
 
-    f = file('/mirror/debian/dists/sid/main/binary-i386/Sources') 
-
-    for src in Sources.iter_paragraphs(f):
-	print src['Package'], src['Version']
+    with open('/mirror/debian/dists/sid/main/binary-i386/Sources') as f:
+        for src in Sources.iter_paragraphs(f):
+            print src['Package'], src['Version']
 
 This method uses python-apt if available to parse the file, since it
 significantly boosts performance. The downside, though, is that yielded
@@ -80,7 +79,8 @@ Sample usage (TODO: Improve)
 
    import deb822 
 
-   d = deb822.dsc(file('foo_1.1.dsc'))
+   with open('foo_1.1.dsc') as f:
+       d = deb822.Dsc(f)
    source = d['Source']
    version = d['Version']
 
diff --git a/examples/deb822/depgraph b/examples/deb822/depgraph
index 388020a..f292e1c 100755
--- a/examples/deb822/depgraph
+++ b/examples/deb822/depgraph
@@ -39,7 +39,7 @@ def main():
         print('  "%s" [label="%s"] ;' % (node, dsc))
 
     print("digraph depgraph {")
-    for pkg in deb822.Packages.iter_paragraphs(file(sys.argv[1])):
+    for pkg in deb822.Packages.iter_paragraphs(open(sys.argv[1])):
         name = pkg['package']
         rels = pkg.relations
         for deps in rels['depends']:
diff --git a/examples/deb822/grep-maintainer b/examples/deb822/grep-maintainer
index 2775dda..b752e2c 100755
--- a/examples/deb822/grep-maintainer
+++ b/examples/deb822/grep-maintainer
@@ -25,7 +25,7 @@ except re.error as e:
     print("Error in the regexp: %s" % (e,), file=sys.stderr)
     sys.exit(1)
 
-for pkg in deb822.Packages.iter_paragraphs(file('/var/lib/dpkg/status')):
+for pkg in deb822.Packages.iter_paragraphs(open('/var/lib/dpkg/status')):
     if 'Maintainer' in pkg and maint_RE.search(pkg['maintainer']):
         print(pkg['package'])
 
diff --git a/examples/deb822/grep_native_packages.py b/examples/deb822/grep_native_packages.py
index dea04f4..896fdef 100755
--- a/examples/deb822/grep_native_packages.py
+++ b/examples/deb822/grep_native_packages.py
@@ -15,7 +15,7 @@ import sys
 from debian import deb822
 
 for fname in sys.argv[1:]:
-    f = file(fname)
+    f = open(fname)
     for stanza in deb822.Sources.iter_paragraphs(f):
         pieces = stanza['version'].split('-')
         if len(pieces) < 2:
diff --git a/examples/debfile/extract_cron b/examples/debfile/extract_cron
index 2c46019..d8f6269 100755
--- a/examples/debfile/extract_cron
+++ b/examples/debfile/extract_cron
@@ -35,7 +35,7 @@ if __name__ == '__main__':
             dir = os.path.dirname(path)
             if not os.path.exists(dir):
                 os.mkdir(dir)
-            out = file(path, 'w')
+            out = open(path, 'w')
             out.write(deb.data.get_content(cron_file))
             out.close()
 
diff --git a/examples/debtags/tagminer b/examples/debtags/tagminer
index ade8be6..470fa33 100755
--- a/examples/debtags/tagminer
+++ b/examples/debtags/tagminer
@@ -96,7 +96,7 @@ def mimetype(fname):
         else:
             xkeys[k] = [v]
     namemagic =  magic.file(fname)
-    contentmagic = magic.buffer(file(fname, "r").read(4096))
+    contentmagic = magic.buffer(open(fname, "r").read(4096))
     return "mimetype" in xkeys and xkeys['mimetype'][0] or contentmagic or namemagic
 
 
diff --git a/lib/debian/deb822.py b/lib/debian/deb822.py
index 4ba6ef3..e8690e2 100644
--- a/lib/debian/deb822.py
+++ b/lib/debian/deb822.py
@@ -267,7 +267,7 @@ class Deb822(Deb822Dict):
         """Create a new Deb822 instance.
 
         :param sequence: a string, or any any object that returns a line of
-            input each time, normally a file().  Alternately, sequence can
+            input each time, normally a file.  Alternately, sequence can
             be a dict that contains the initial key-value pairs.
 
         :param fields: if given, it is interpreted as a list of fields that
@@ -304,7 +304,7 @@ class Deb822(Deb822Dict):
 
         :param fields: likewise.
 
-        :param use_apt_pkg: if sequence is a file(), apt_pkg will be used 
+        :param use_apt_pkg: if sequence is a file, apt_pkg will be used
             if available to parse the file, since it's much much faster.  Set
             this parameter to False to disable using apt_pkg.
         :param shared_storage: not used, here for historical reasons.  Deb822
@@ -776,7 +776,8 @@ class GpgInfo(dict):
 
         See GpgInfo.from_sequence.
         """
-        return cls.from_sequence(file(target), *args, **kwargs)
+        with open(target) as target_file:
+            return cls.from_sequence(target_file, *args, **kwargs)
 
 
 class PkgRelation(object):
diff --git a/lib/debian/debian_support.py b/lib/debian/debian_support.py
index a5af828..b70c9b5 100644
--- a/lib/debian/debian_support.py
+++ b/lib/debian/debian_support.py
@@ -286,7 +286,7 @@ class PackageFile:
                   file with the indicated name.
         """
         if file_obj is None:
-            file_obj = file(name)
+            file_obj = open(name)
         self.name = name
         self.file = file_obj
         self.lineno = 0
@@ -440,7 +440,7 @@ def replace_file(lines, local):
     import os.path
 
     local_new = local + '.new'
-    new_file = file(local_new, 'w+')
+    new_file = open(local_new, 'w+')
 
     try:
         for l in lines:
@@ -498,7 +498,7 @@ def update_file(remote, local, verbose=None):
     """
 
     try:
-        local_file = file(local)
+        local_file = open(local)
     except IOError:
         if verbose:
             print("update_file: no local copy, downloading full file")
diff --git a/tests/test_deb822.py b/tests/test_deb822.py
index 1b5c665..e2b1818 100755
--- a/tests/test_deb822.py
+++ b/tests/test_deb822.py
@@ -688,11 +688,11 @@ Description: python modules to work with Debian-related data formats
         objects = []
         objects.append(deb822.Deb822(UNPARSED_PACKAGE))
         objects.append(deb822.Deb822(CHANGES_FILE))
-        objects.extend(deb822.Deb822.iter_paragraphs(file('test_Packages')))
-        objects.extend(deb822.Packages.iter_paragraphs(file('test_Packages')))
-        objects.extend(deb822.Deb822.iter_paragraphs(file('test_Sources')))
+        objects.extend(deb822.Deb822.iter_paragraphs(open('test_Packages')))
+        objects.extend(deb822.Packages.iter_paragraphs(open('test_Packages')))
+        objects.extend(deb822.Deb822.iter_paragraphs(open('test_Sources')))
         objects.extend(deb822.Deb822.iter_paragraphs(
-                         file('test_Sources.iso8859-1'), encoding="iso8859-1"))
+                         open('test_Sources.iso8859-1'), encoding="iso8859-1"))
         for d in objects:
             for value in d.values():
                 self.assert_(isinstance(value, unicode))
@@ -703,16 +703,16 @@ Description: python modules to work with Debian-related data formats
         multi.append(deb822.Changes(CHANGES_FILE))
         multi.append(deb822.Changes(SIGNED_CHECKSUM_CHANGES_FILE
                                     % CHECKSUM_CHANGES_FILE))
-        multi.extend(deb822.Sources.iter_paragraphs(file('test_Sources')))
+        multi.extend(deb822.Sources.iter_paragraphs(open('test_Sources')))
         for d in multi:
             for key, value in d.items():
                 if key.lower() not in d.__class__._multivalued_fields:
                     self.assert_(isinstance(value, unicode))
 
     def test_encoding_integrity(self):
-        utf8 = list(deb822.Deb822.iter_paragraphs(file('test_Sources')))
+        utf8 = list(deb822.Deb822.iter_paragraphs(open('test_Sources')))
         latin1 = list(deb822.Deb822.iter_paragraphs(
-                                                file('test_Sources.iso8859-1'),
+                                                open('test_Sources.iso8859-1'),
                                                 encoding='iso8859-1'))
 
         # dump() with no fd returns a unicode object - both should be identical
@@ -723,9 +723,9 @@ Description: python modules to work with Debian-related data formats
         # XXX: The way multiline fields parsing works, we can't guarantee
         # that trailing whitespace is reproduced.
         utf8_contents = "\n".join([line.rstrip() for line in
-                                   file('test_Sources')] + [''])
+                                   open('test_Sources')] + [''])
         latin1_contents = "\n".join([line.rstrip() for line in
-                                     file('test_Sources.iso8859-1')] + [''])
+                                     open('test_Sources.iso8859-1')] + [''])
 
         utf8_to_latin1 = StringIO()
         for d in utf8:
@@ -753,8 +753,8 @@ Description: python modules to work with Debian-related data formats
         warnings.filterwarnings(action='ignore', category=UnicodeWarning)
 
         filename = 'test_Sources.mixed_encoding'
-        for paragraphs in [deb822.Sources.iter_paragraphs(file(filename)),
-                           deb822.Sources.iter_paragraphs(file(filename),
+        for paragraphs in [deb822.Sources.iter_paragraphs(open(filename)),
+                           deb822.Sources.iter_paragraphs(open(filename),
                                                           use_apt_pkg=False)]:
             p1 = paragraphs.next()
             self.assertEqual(p1['maintainer'],
@@ -818,7 +818,7 @@ Description: python modules to work with Debian-related data formats
 class TestPkgRelations(unittest.TestCase):
 
     def test_packages(self):
-        pkgs = deb822.Packages.iter_paragraphs(file('test_Packages'))
+        pkgs = deb822.Packages.iter_paragraphs(open('test_Packages'))
         pkg1 = pkgs.next()
         rel1 = {'breaks': [],
                 'conflicts': [],
@@ -893,7 +893,7 @@ class TestPkgRelations(unittest.TestCase):
                             src_rel)))
 
     def test_sources(self):
-        pkgs = deb822.Sources.iter_paragraphs(file('test_Sources'))
+        pkgs = deb822.Sources.iter_paragraphs(open('test_Sources'))
         pkg1 = pkgs.next()
         rel1 = {'build-conflicts': [],
                 'build-conflicts-indep': [],
-- 
1.7.2.5





More information about the pkg-python-debian-commits mailing list