Skip to content

Commit e2151d0

Browse files
committed
Use the open() context manager, supported since Python 2.5
1 parent 7e6cadf commit e2151d0

1 file changed

Lines changed: 9 additions & 13 deletions

File tree

pep8.py

Lines changed: 9 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,8 @@
4444
700 statements
4545
900 syntax error
4646
"""
47+
from __future__ import with_statement
48+
4749
__version__ = '1.5.2a0'
4850

4951
import os
@@ -1039,29 +1041,23 @@ def python_3000_backticks(logical_line):
10391041
# Python 2: implicit encoding.
10401042
def readlines(filename):
10411043
"""Read the source code."""
1042-
f = open(filename)
1043-
try:
1044+
with open(filename) as f:
10441045
return f.readlines()
1045-
finally:
1046-
f.close()
10471046
isidentifier = re.compile(r'[a-zA-Z_]\w*').match
10481047
stdin_get_value = sys.stdin.read
10491048
else:
10501049
# Python 3
10511050
def readlines(filename):
10521051
"""Read the source code."""
1053-
f = open(filename, 'rb')
10541052
try:
1055-
(coding, lines) = tokenize.detect_encoding(f.readline)
1056-
f = TextIOWrapper(f, coding, line_buffering=True)
1057-
return [l.decode(coding) for l in lines] + f.readlines()
1053+
with open(filename, 'rb') as f:
1054+
(coding, lines) = tokenize.detect_encoding(f.readline)
1055+
f = TextIOWrapper(f, coding, line_buffering=True)
1056+
return [l.decode(coding) for l in lines] + f.readlines()
10581057
except (LookupError, SyntaxError, UnicodeError):
1059-
f.close()
10601058
# Fall back if files are improperly declared
1061-
f = open(filename, encoding='latin-1')
1062-
return f.readlines()
1063-
finally:
1064-
f.close()
1059+
with open(filename, encoding='latin-1') as f:
1060+
return f.readlines()
10651061
isidentifier = str.isidentifier
10661062

10671063
def stdin_get_value():

0 commit comments

Comments
 (0)