Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 92f60ed

Browse files
committed
More proper closing of files
1 parent 73315e9 commit 92f60ed

7 files changed

Lines changed: 83 additions & 58 deletions

File tree

Lib/doctest.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -214,7 +214,8 @@ def _load_testfile(filename, package, module_relative, encoding):
214214
# get_data() opens files as 'rb', so one must do the equivalent
215215
# conversion as universal newlines would do.
216216
return file_contents.replace(os.linesep, '\n'), filename
217-
return open(filename, encoding=encoding).read(), filename
217+
with open(filename, encoding=encoding) as f:
218+
return f.read(), filename
218219

219220
def _indent(s, indent=4):
220221
"""
@@ -2523,7 +2524,8 @@ def debug_script(src, pm=False, globs=None):
25232524

25242525
if pm:
25252526
try:
2526-
exec(open(srcfilename).read(), globs, globs)
2527+
with open(srcfilename) as f:
2528+
exec(f.read(), globs, globs)
25272529
except:
25282530
print(sys.exc_info()[1])
25292531
pdb.post_mortem(sys.exc_info()[2])

Lib/test/test_decimal.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -225,14 +225,15 @@ def eval_file(self, file):
225225
if skip_expected:
226226
raise unittest.SkipTest
227227
return
228-
for line in open(file):
229-
line = line.replace('\r\n', '').replace('\n', '')
230-
#print line
231-
try:
232-
t = self.eval_line(line)
233-
except DecimalException as exception:
234-
#Exception raised where there shoudn't have been one.
235-
self.fail('Exception "'+exception.__class__.__name__ + '" raised on line '+line)
228+
with open(file) as f:
229+
for line in f:
230+
line = line.replace('\r\n', '').replace('\n', '')
231+
#print line
232+
try:
233+
t = self.eval_line(line)
234+
except DecimalException as exception:
235+
#Exception raised where there shoudn't have been one.
236+
self.fail('Exception "'+exception.__class__.__name__ + '" raised on line '+line)
236237

237238
return
238239

Lib/test/test_modulefinder.py

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -204,11 +204,17 @@ def open_file(path):
204204

205205
def create_package(source):
206206
ofi = None
207-
for line in source.splitlines():
208-
if line.startswith(" ") or line.startswith("\t"):
209-
ofi.write(line.strip() + "\n")
210-
else:
211-
ofi = open_file(os.path.join(TEST_DIR, line.strip()))
207+
try:
208+
for line in source.splitlines():
209+
if line.startswith(" ") or line.startswith("\t"):
210+
ofi.write(line.strip() + "\n")
211+
else:
212+
if ofi:
213+
ofi.close()
214+
ofi = open_file(os.path.join(TEST_DIR, line.strip()))
215+
finally:
216+
if ofi:
217+
ofi.close()
212218

213219
class ModuleFinderTest(unittest.TestCase):
214220
def _do_test(self, info, report=False):

Lib/test/test_multibytecodec.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,8 +48,8 @@ def test_errorcallback_longindex(self):
4848
def test_codingspec(self):
4949
try:
5050
for enc in ALL_CJKENCODINGS:
51-
print('# coding:', enc, file=io.open(TESTFN, 'w'))
52-
exec(open(TESTFN).read())
51+
code = '# coding: {}\n'.format(enc)
52+
exec(code)
5353
finally:
5454
support.unlink(TESTFN)
5555

Lib/test/test_multibytecodec_support.py

Lines changed: 29 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -278,7 +278,7 @@ class TestBase_Mapping(unittest.TestCase):
278278
def __init__(self, *args, **kw):
279279
unittest.TestCase.__init__(self, *args, **kw)
280280
try:
281-
self.open_mapping_file() # test it to report the error early
281+
self.open_mapping_file().close() # test it to report the error early
282282
except (IOError, HTTPException):
283283
self.skipTest("Could not retrieve "+self.mapfileurl)
284284

@@ -295,36 +295,38 @@ def _test_mapping_file_plain(self):
295295
unichrs = lambda s: ''.join(map(chr, map(eval, s.split('+'))))
296296
urt_wa = {}
297297

298-
for line in self.open_mapping_file():
299-
if not line:
300-
break
301-
data = line.split('#')[0].strip().split()
302-
if len(data) != 2:
303-
continue
304-
305-
csetval = eval(data[0])
306-
if csetval <= 0x7F:
307-
csetch = bytes([csetval & 0xff])
308-
elif csetval >= 0x1000000:
309-
csetch = bytes([(csetval >> 24), ((csetval >> 16) & 0xff),
310-
((csetval >> 8) & 0xff), (csetval & 0xff)])
311-
elif csetval >= 0x10000:
312-
csetch = bytes([(csetval >> 16), ((csetval >> 8) & 0xff),
313-
(csetval & 0xff)])
314-
elif csetval >= 0x100:
315-
csetch = bytes([(csetval >> 8), (csetval & 0xff)])
316-
else:
317-
continue
298+
with self.open_mapping_file() as f:
299+
for line in f:
300+
if not line:
301+
break
302+
data = line.split('#')[0].strip().split()
303+
if len(data) != 2:
304+
continue
305+
306+
csetval = eval(data[0])
307+
if csetval <= 0x7F:
308+
csetch = bytes([csetval & 0xff])
309+
elif csetval >= 0x1000000:
310+
csetch = bytes([(csetval >> 24), ((csetval >> 16) & 0xff),
311+
((csetval >> 8) & 0xff), (csetval & 0xff)])
312+
elif csetval >= 0x10000:
313+
csetch = bytes([(csetval >> 16), ((csetval >> 8) & 0xff),
314+
(csetval & 0xff)])
315+
elif csetval >= 0x100:
316+
csetch = bytes([(csetval >> 8), (csetval & 0xff)])
317+
else:
318+
continue
318319

319-
unich = unichrs(data[1])
320-
if ord(unich) == 0xfffd or unich in urt_wa:
321-
continue
322-
urt_wa[unich] = csetch
320+
unich = unichrs(data[1])
321+
if ord(unich) == 0xfffd or unich in urt_wa:
322+
continue
323+
urt_wa[unich] = csetch
323324

324-
self._testpoint(csetch, unich)
325+
self._testpoint(csetch, unich)
325326

326327
def _test_mapping_file_ucm(self):
327-
ucmdata = self.open_mapping_file().read()
328+
with self.open_mapping_file() as f:
329+
ucmdata = f.read()
328330
uc = re.findall('<a u="([A-F0-9]{4})" b="([0-9A-F ]+)"/>', ucmdata)
329331
for uni, coded in uc:
330332
unich = chr(int(uni, 16))

Lib/test/test_pipes.py

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -23,17 +23,21 @@ def testSimplePipe1(self):
2323
f = t.open(TESTFN, 'w')
2424
f.write('hello world #1')
2525
f.close()
26-
self.assertEqual(open(TESTFN).read(), 'HELLO WORLD #1')
26+
with open(TESTFN) as f:
27+
self.assertEqual(f.read(), 'HELLO WORLD #1')
2728

2829
def testSimplePipe2(self):
29-
open(TESTFN, 'w').write('hello world #2')
30+
with open(TESTFN, 'w') as f:
31+
f.write('hello world #2')
3032
t = pipes.Template()
3133
t.append(s_command + ' < $IN > $OUT', pipes.FILEIN_FILEOUT)
3234
t.copy(TESTFN, TESTFN2)
33-
self.assertEqual(open(TESTFN2).read(), 'HELLO WORLD #2')
35+
with open(TESTFN2) as f:
36+
self.assertEqual(f.read(), 'HELLO WORLD #2')
3437

3538
def testSimplePipe3(self):
36-
open(TESTFN, 'w').write('hello world #2')
39+
with open(TESTFN, 'w') as f:
40+
f.write('hello world #2')
3741
t = pipes.Template()
3842
t.append(s_command + ' < $IN', pipes.FILEIN_STDOUT)
3943
f = t.open(TESTFN, 'r')
@@ -45,16 +49,20 @@ def testSimplePipe3(self):
4549
def testEmptyPipeline1(self):
4650
# copy through empty pipe
4751
d = 'empty pipeline test COPY'
48-
open(TESTFN, 'w').write(d)
49-
open(TESTFN2, 'w').write('')
52+
with open(TESTFN, 'w') as f:
53+
f.write(d)
54+
with open(TESTFN2, 'w') as f:
55+
f.write('')
5056
t=pipes.Template()
5157
t.copy(TESTFN, TESTFN2)
52-
self.assertEqual(open(TESTFN2).read(), d)
58+
with open(TESTFN2) as f:
59+
self.assertEqual(f.read(), d)
5360

5461
def testEmptyPipeline2(self):
5562
# read through empty pipe
5663
d = 'empty pipeline test READ'
57-
open(TESTFN, 'w').write(d)
64+
with open(TESTFN, 'w') as f:
65+
f.write(d)
5866
t=pipes.Template()
5967
f = t.open(TESTFN, 'r')
6068
try:
@@ -66,8 +74,10 @@ def testEmptyPipeline3(self):
6674
# write through empty pipe
6775
d = 'empty pipeline test WRITE'
6876
t = pipes.Template()
69-
t.open(TESTFN, 'w').write(d)
70-
self.assertEqual(open(TESTFN).read(), d)
77+
with t.open(TESTFN, 'w') as f:
78+
f.write(d)
79+
with open(TESTFN) as f:
80+
self.assertEqual(f.read(), d)
7181

7282
def testQuoting(self):
7383
safeunquoted = string.ascii_letters + string.digits + '@%_-+=:,./'

Lib/test/test_shutil.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -285,15 +285,17 @@ def test_dont_copy_file_onto_link_to_itself(self):
285285
if hasattr(os, "link"):
286286
os.link(src, dst)
287287
self.assertRaises(shutil.Error, shutil.copyfile, src, dst)
288-
self.assertEqual(open(src,'r').read(), 'cheddar')
288+
with open(src, 'r') as f:
289+
self.assertEqual(f.read(), 'cheddar')
289290
os.remove(dst)
290291

291292
# Using `src` here would mean we end up with a symlink pointing
292293
# to TESTFN/TESTFN/cheese, while it should point at
293294
# TESTFN/cheese.
294295
os.symlink('cheese', dst)
295296
self.assertRaises(shutil.Error, shutil.copyfile, src, dst)
296-
self.assertEqual(open(src,'r').read(), 'cheddar')
297+
with open(src, 'r') as f:
298+
self.assertEqual(f.read(), 'cheddar')
297299
os.remove(dst)
298300
finally:
299301
try:
@@ -690,9 +692,11 @@ def tearDown(self):
690692
pass
691693

692694
def _check_move_file(self, src, dst, real_dst):
693-
contents = open(src, "rb").read()
695+
with open(src, "rb") as f:
696+
contents = f.read()
694697
shutil.move(src, dst)
695-
self.assertEqual(contents, open(real_dst, "rb").read())
698+
with open(real_dst, "rb") as f:
699+
self.assertEqual(contents, f.read())
696700
self.assertFalse(os.path.exists(src))
697701

698702
def _check_move_dir(self, src, dst, real_dst):

0 commit comments

Comments
 (0)