diff --git a/libhts/libhts.py b/libhts/libhts.py
index 4e633984a07a2bc0f9d6f6daf8c0cbe9c3fc7959..5932deb011607f62c73aec96404c71c8880cb11c 100644
--- a/libhts/libhts.py
+++ b/libhts/libhts.py
@@ -188,19 +188,19 @@ def id_list_gtf2bed(identifiers, gtf_filename, feature_type="transcript", id_kwd
     in the feature annotations in the gtf_file. These feature IDs will be
     matched against the elements in *identifiers*.
     """
-    gtf_file = open(gtf_filename, "r")
-    gtf = BedTool(gtf_file)
-    if identifiers:
-        ids = set(identifiers)
-        def feature_filter(feature):
-            return feature[2] == feature_type and feature[id_kwd] in ids
-        return gtf.filter(feature_filter)
-    else:
-        # https://stackoverflow.com/a/13243870/1878788
-        def empty_bed_generator():
-            return
-            yield
-        return empty_bed_generator()
+    with open(gtf_filename, "r") as gtf_file:
+        gtf = BedTool(gtf_file)
+        if identifiers:
+            ids = set(identifiers)
+            def feature_filter(feature):
+                return feature[2] == feature_type and feature[id_kwd] in ids
+            return gtf.filter(feature_filter)
+        else:
+            # https://stackoverflow.com/a/13243870/1878788
+            def empty_bed_generator():
+                return
+                yield
+            return empty_bed_generator()
 
 
 def make_empty_bigwig(filename, chrom_sizes):