Skip to content

Commit 2d70e9f

Browse files
BoboTiGyanglbme
authored andcommitted
Fix ResourceWarning: unclosed file (TheAlgorithms#681)
Signed-off-by: Mickaël Schoentgen <contact@tiger-222.fr>
1 parent 3dc5052 commit 2d70e9f

10 files changed

+102
-108
lines changed

ciphers/rsa_cipher.py

+6-8
Original file line numberDiff line numberDiff line change
@@ -80,9 +80,8 @@ def decryptMessage(encryptedBlocks, messageLength, key, blockSize=DEFAULT_BLOCK_
8080

8181

8282
def readKeyFile(keyFilename):
83-
fo = open(keyFilename)
84-
content = fo.read()
85-
fo.close()
83+
with open(keyFilename) as fo:
84+
content = fo.read()
8685
keySize, n, EorD = content.split(',')
8786
return (int(keySize), int(n), int(EorD))
8887

@@ -98,16 +97,15 @@ def encryptAndWriteToFile(messageFilename, keyFilename, message, blockSize=DEFAU
9897
encryptedBlocks[i] = str(encryptedBlocks[i])
9998
encryptedContent = ','.join(encryptedBlocks)
10099
encryptedContent = '%s_%s_%s' % (len(message), blockSize, encryptedContent)
101-
fo = open(messageFilename, 'w')
102-
fo.write(encryptedContent)
103-
fo.close()
100+
with open(messageFilename, 'w') as fo:
101+
fo.write(encryptedContent)
104102
return encryptedContent
105103

106104

107105
def readFromFileAndDecrypt(messageFilename, keyFilename):
108106
keySize, n, d = readKeyFile(keyFilename)
109-
fo = open(messageFilename)
110-
content = fo.read()
107+
with open(messageFilename) as fo:
108+
content = fo.read()
111109
messageLength, blockSize, encryptedMessage = content.split('_')
112110
messageLength = int(messageLength)
113111
blockSize = int(blockSize)

ciphers/transposition_cipher_encrypt_decrypt_file.py

+6-5
Original file line numberDiff line numberDiff line change
@@ -19,15 +19,16 @@ def main():
1919

2020
startTime = time.time()
2121
if mode.lower().startswith('e'):
22-
content = open(inputFile).read()
22+
with open(inputFile) as f:
23+
content = f.read()
2324
translated = transCipher.encryptMessage(key, content)
2425
elif mode.lower().startswith('d'):
25-
content = open(outputFile).read()
26+
with open(outputFile) as f:
27+
content = f.read()
2628
translated =transCipher .decryptMessage(key, content)
2729

28-
outputObj = open(outputFile, 'w')
29-
outputObj.write(translated)
30-
outputObj.close()
30+
with open(outputFile, 'w') as outputObj:
31+
outputObj.write(translated)
3132

3233
totalTime = round(time.time() - startTime, 2)
3334
print(('Done (', totalTime, 'seconds )'))

file_transfer_protocol/ftp_client_server.py

+6-7
Original file line numberDiff line numberDiff line change
@@ -17,13 +17,12 @@
1717
print('Server received', repr(data))
1818

1919
filename = 'mytext.txt'
20-
f = open(filename, 'rb')
21-
in_data = f.read(1024)
22-
while (in_data):
23-
conn.send(in_data)
24-
print('Sent ', repr(in_data))
25-
in_data = f.read(1024)
26-
f.close()
20+
with open(filename, 'rb') as f:
21+
in_data = f.read(1024)
22+
while in_data:
23+
conn.send(in_data)
24+
print('Sent ', repr(in_data))
25+
in_data = f.read(1024)
2726

2827
print('Done sending')
2928
conn.send('Thank you for connecting')

file_transfer_protocol/ftp_send_receive.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -20,10 +20,9 @@
2020

2121
def ReceiveFile():
2222
FileName = 'example.txt' """ Enter the location of the file """
23-
LocalFile = open(FileName, 'wb')
24-
ftp.retrbinary('RETR ' + FileName, LocalFile.write, 1024)
23+
with open(FileName, 'wb') as LocalFile:
24+
ftp.retrbinary('RETR ' + FileName, LocalFile.write, 1024)
2525
ftp.quit()
26-
LocalFile.close()
2726

2827
"""
2928
The file which will be sent via the FTP server
@@ -32,5 +31,6 @@ def ReceiveFile():
3231

3332
def SendFile():
3433
FileName = 'example.txt' """ Enter the name of the file """
35-
ftp.storbinary('STOR ' + FileName, open(FileName, 'rb'))
34+
with open(FileName, 'rb') as LocalFile:
35+
ftp.storbinary('STOR ' + FileName, LocalFile)
3636
ftp.quit()

hashes/sha1.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,8 @@ def main():
137137
input_string = args.input_string
138138
#In any case hash input should be a bytestring
139139
if args.input_file:
140-
hash_input = open(args.input_file, 'rb').read()
140+
with open(args.input_file, 'rb') as f:
141+
hash_input = f.read()
141142
else:
142143
hash_input = bytes(input_string, 'utf-8')
143144
print(SHA1Hash(hash_input).final_hash())

other/anagrams.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,8 @@
44
start_time = time.time()
55
print('creating word list...')
66
path = os.path.split(os.path.realpath(__file__))
7-
word_list = sorted(list(set([word.strip().lower() for word in open(path[0] + '/words')])))
7+
with open(path[0] + '/words') as f:
8+
word_list = sorted(list(set([word.strip().lower() for word in f])))
89

910
def signature(word):
1011
return ''.join(sorted(word))

other/detecting_english_programmatically.py

+3-4
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,10 @@
55

66
def loadDictionary():
77
path = os.path.split(os.path.realpath(__file__))
8-
dictionaryFile = open(path[0] + '/Dictionary.txt')
98
englishWords = {}
10-
for word in dictionaryFile.read().split('\n'):
11-
englishWords[word] = None
12-
dictionaryFile.close()
9+
with open(path[0] + '/Dictionary.txt') as dictionaryFile:
10+
for word in dictionaryFile.read().split('\n'):
11+
englishWords[word] = None
1312
return englishWords
1413

1514
ENGLISH_WORDS = loadDictionary()

searches/tabu_search.py

+16-18
Original file line numberDiff line numberDiff line change
@@ -45,24 +45,23 @@ def generate_neighbours(path):
4545
the node 'c' with distance 18, the node 'd' with distance 22 and the node 'e' with distance 26.
4646
4747
"""
48-
f = open(path, "r")
4948

5049
dict_of_neighbours = {}
5150

52-
for line in f:
53-
if line.split()[0] not in dict_of_neighbours:
54-
_list = list()
55-
_list.append([line.split()[1], line.split()[2]])
56-
dict_of_neighbours[line.split()[0]] = _list
57-
else:
58-
dict_of_neighbours[line.split()[0]].append([line.split()[1], line.split()[2]])
59-
if line.split()[1] not in dict_of_neighbours:
60-
_list = list()
61-
_list.append([line.split()[0], line.split()[2]])
62-
dict_of_neighbours[line.split()[1]] = _list
63-
else:
64-
dict_of_neighbours[line.split()[1]].append([line.split()[0], line.split()[2]])
65-
f.close()
51+
with open(path) as f:
52+
for line in f:
53+
if line.split()[0] not in dict_of_neighbours:
54+
_list = list()
55+
_list.append([line.split()[1], line.split()[2]])
56+
dict_of_neighbours[line.split()[0]] = _list
57+
else:
58+
dict_of_neighbours[line.split()[0]].append([line.split()[1], line.split()[2]])
59+
if line.split()[1] not in dict_of_neighbours:
60+
_list = list()
61+
_list.append([line.split()[0], line.split()[2]])
62+
dict_of_neighbours[line.split()[1]] = _list
63+
else:
64+
dict_of_neighbours[line.split()[1]].append([line.split()[0], line.split()[2]])
6665

6766
return dict_of_neighbours
6867

@@ -84,16 +83,15 @@ def generate_first_solution(path, dict_of_neighbours):
8483
8584
"""
8685

87-
f = open(path, "r")
88-
start_node = f.read(1)
86+
with open(path) as f:
87+
start_node = f.read(1)
8988
end_node = start_node
9089

9190
first_solution = []
9291

9392
visiting = start_node
9493

9594
distance_of_first_solution = 0
96-
f.close()
9795
while visiting not in first_solution:
9896
minim = 10000
9997
for k in dict_of_neighbours[visiting]:

sorts/external-sort.py

+18-20
Original file line numberDiff line numberDiff line change
@@ -15,31 +15,29 @@ def __init__(self, filename):
1515

1616
def write_block(self, data, block_number):
1717
filename = self.BLOCK_FILENAME_FORMAT.format(block_number)
18-
file = open(filename, 'w')
19-
file.write(data)
20-
file.close()
18+
with open(filename, 'w') as file:
19+
file.write(data)
2120
self.block_filenames.append(filename)
2221

2322
def get_block_filenames(self):
2423
return self.block_filenames
2524

2625
def split(self, block_size, sort_key=None):
27-
file = open(self.filename, 'r')
2826
i = 0
27+
with open(self.filename) as file:
28+
while True:
29+
lines = file.readlines(block_size)
2930

30-
while True:
31-
lines = file.readlines(block_size)
31+
if lines == []:
32+
break
3233

33-
if lines == []:
34-
break
34+
if sort_key is None:
35+
lines.sort()
36+
else:
37+
lines.sort(key=sort_key)
3538

36-
if sort_key is None:
37-
lines.sort()
38-
else:
39-
lines.sort(key=sort_key)
40-
41-
self.write_block(''.join(lines), i)
42-
i += 1
39+
self.write_block(''.join(lines), i)
40+
i += 1
4341

4442
def cleanup(self):
4543
map(lambda f: os.remove(f), self.block_filenames)
@@ -74,6 +72,7 @@ def refresh(self):
7472

7573
if self.buffers[i] == '':
7674
self.empty.add(i)
75+
self.files[i].close()
7776

7877
if len(self.empty) == self.num_buffers:
7978
return False
@@ -92,12 +91,11 @@ def __init__(self, merge_strategy):
9291
self.merge_strategy = merge_strategy
9392

9493
def merge(self, filenames, outfilename, buffer_size):
95-
outfile = open(outfilename, 'w', buffer_size)
9694
buffers = FilesArray(self.get_file_handles(filenames, buffer_size))
97-
98-
while buffers.refresh():
99-
min_index = self.merge_strategy.select(buffers.get_dict())
100-
outfile.write(buffers.unshift(min_index))
95+
with open(outfilename, 'w', buffer_size) as outfile:
96+
while buffers.refresh():
97+
min_index = self.merge_strategy.select(buffers.get_dict())
98+
outfile.write(buffers.unshift(min_index))
10199

102100
def get_file_handles(self, filenames, buffer_size):
103101
files = {}

strings/min_cost_string_conversion.py

+39-40
Original file line numberDiff line numberDiff line change
@@ -73,50 +73,49 @@ def assemble_transformation(ops, i, j):
7373
m = len(operations)
7474
n = len(operations[0])
7575
sequence = assemble_transformation(operations, m-1, n-1)
76-
77-
file = open('min_cost.txt', 'w')
7876

7977
string = list('Python')
8078
i = 0
8179
cost = 0
82-
for op in sequence:
83-
print(''.join(string))
84-
85-
if op[0] == 'C':
86-
file.write('%-16s' % 'Copy %c' % op[1])
87-
file.write('\t\t\t' + ''.join(string))
88-
file.write('\r\n')
89-
90-
cost -= 1
91-
elif op[0] == 'R':
92-
string[i] = op[2]
93-
94-
file.write('%-16s' % ('Replace %c' % op[1] + ' with ' + str(op[2])))
95-
file.write('\t\t' + ''.join(string))
96-
file.write('\r\n')
97-
98-
cost += 1
99-
elif op[0] == 'D':
100-
string.pop(i)
101-
102-
file.write('%-16s' % 'Delete %c' % op[1])
103-
file.write('\t\t\t' + ''.join(string))
104-
file.write('\r\n')
105-
106-
cost += 2
107-
else:
108-
string.insert(i, op[1])
80+
81+
with open('min_cost.txt', 'w') as file:
82+
for op in sequence:
83+
print(''.join(string))
84+
85+
if op[0] == 'C':
86+
file.write('%-16s' % 'Copy %c' % op[1])
87+
file.write('\t\t\t' + ''.join(string))
88+
file.write('\r\n')
89+
90+
cost -= 1
91+
elif op[0] == 'R':
92+
string[i] = op[2]
93+
94+
file.write('%-16s' % ('Replace %c' % op[1] + ' with ' + str(op[2])))
95+
file.write('\t\t' + ''.join(string))
96+
file.write('\r\n')
97+
98+
cost += 1
99+
elif op[0] == 'D':
100+
string.pop(i)
101+
102+
file.write('%-16s' % 'Delete %c' % op[1])
103+
file.write('\t\t\t' + ''.join(string))
104+
file.write('\r\n')
105+
106+
cost += 2
107+
else:
108+
string.insert(i, op[1])
109109

110-
file.write('%-16s' % 'Insert %c' % op[1])
111-
file.write('\t\t\t' + ''.join(string))
112-
file.write('\r\n')
113-
114-
cost += 2
110+
file.write('%-16s' % 'Insert %c' % op[1])
111+
file.write('\t\t\t' + ''.join(string))
112+
file.write('\r\n')
113+
114+
cost += 2
115115

116-
i += 1
116+
i += 1
117117

118-
print(''.join(string))
119-
print('Cost: ', cost)
120-
121-
file.write('\r\nMinimum cost: ' + str(cost))
122-
file.close()
118+
print(''.join(string))
119+
print('Cost: ', cost)
120+
121+
file.write('\r\nMinimum cost: ' + str(cost))

0 commit comments

Comments
 (0)