Skip to content

Commit

Permalink
Fix ResourceWarning: unclosed file (#681)
Browse files Browse the repository at this point in the history
Signed-off-by: Mickaël Schoentgen <contact@tiger-222.fr>
  • Loading branch information
BoboTiG authored and yanglbme committed Jan 8, 2019
1 parent 3dc5052 commit 2d70e9f
Show file tree
Hide file tree
Showing 10 changed files with 102 additions and 108 deletions.
14 changes: 6 additions & 8 deletions ciphers/rsa_cipher.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,9 +80,8 @@ def decryptMessage(encryptedBlocks, messageLength, key, blockSize=DEFAULT_BLOCK_


def readKeyFile(keyFilename):
fo = open(keyFilename)
content = fo.read()
fo.close()
with open(keyFilename) as fo:
content = fo.read()
keySize, n, EorD = content.split(',')
return (int(keySize), int(n), int(EorD))

Expand All @@ -98,16 +97,15 @@ def encryptAndWriteToFile(messageFilename, keyFilename, message, blockSize=DEFAU
encryptedBlocks[i] = str(encryptedBlocks[i])
encryptedContent = ','.join(encryptedBlocks)
encryptedContent = '%s_%s_%s' % (len(message), blockSize, encryptedContent)
fo = open(messageFilename, 'w')
fo.write(encryptedContent)
fo.close()
with open(messageFilename, 'w') as fo:
fo.write(encryptedContent)
return encryptedContent


def readFromFileAndDecrypt(messageFilename, keyFilename):
keySize, n, d = readKeyFile(keyFilename)
fo = open(messageFilename)
content = fo.read()
with open(messageFilename) as fo:
content = fo.read()
messageLength, blockSize, encryptedMessage = content.split('_')
messageLength = int(messageLength)
blockSize = int(blockSize)
Expand Down
11 changes: 6 additions & 5 deletions ciphers/transposition_cipher_encrypt_decrypt_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,16 @@ def main():

startTime = time.time()
if mode.lower().startswith('e'):
content = open(inputFile).read()
with open(inputFile) as f:
content = f.read()
translated = transCipher.encryptMessage(key, content)
elif mode.lower().startswith('d'):
content = open(outputFile).read()
with open(outputFile) as f:
content = f.read()
translated =transCipher .decryptMessage(key, content)

outputObj = open(outputFile, 'w')
outputObj.write(translated)
outputObj.close()
with open(outputFile, 'w') as outputObj:
outputObj.write(translated)

totalTime = round(time.time() - startTime, 2)
print(('Done (', totalTime, 'seconds )'))
Expand Down
13 changes: 6 additions & 7 deletions file_transfer_protocol/ftp_client_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,12 @@
print('Server received', repr(data))

filename = 'mytext.txt'
f = open(filename, 'rb')
in_data = f.read(1024)
while (in_data):
conn.send(in_data)
print('Sent ', repr(in_data))
in_data = f.read(1024)
f.close()
with open(filename, 'rb') as f:
in_data = f.read(1024)
while in_data:
conn.send(in_data)
print('Sent ', repr(in_data))
in_data = f.read(1024)

print('Done sending')
conn.send('Thank you for connecting')
Expand Down
8 changes: 4 additions & 4 deletions file_transfer_protocol/ftp_send_receive.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,9 @@

def ReceiveFile():
FileName = 'example.txt' """ Enter the location of the file """
LocalFile = open(FileName, 'wb')
ftp.retrbinary('RETR ' + FileName, LocalFile.write, 1024)
with open(FileName, 'wb') as LocalFile:
ftp.retrbinary('RETR ' + FileName, LocalFile.write, 1024)
ftp.quit()
LocalFile.close()

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

def SendFile():
FileName = 'example.txt' """ Enter the name of the file """
ftp.storbinary('STOR ' + FileName, open(FileName, 'rb'))
with open(FileName, 'rb') as LocalFile:
ftp.storbinary('STOR ' + FileName, LocalFile)
ftp.quit()
3 changes: 2 additions & 1 deletion hashes/sha1.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,8 @@ def main():
input_string = args.input_string
#In any case hash input should be a bytestring
if args.input_file:
hash_input = open(args.input_file, 'rb').read()
with open(args.input_file, 'rb') as f:
hash_input = f.read()
else:
hash_input = bytes(input_string, 'utf-8')
print(SHA1Hash(hash_input).final_hash())
Expand Down
3 changes: 2 additions & 1 deletion other/anagrams.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
start_time = time.time()
print('creating word list...')
path = os.path.split(os.path.realpath(__file__))
word_list = sorted(list(set([word.strip().lower() for word in open(path[0] + '/words')])))
with open(path[0] + '/words') as f:
word_list = sorted(list(set([word.strip().lower() for word in f])))

def signature(word):
return ''.join(sorted(word))
Expand Down
7 changes: 3 additions & 4 deletions other/detecting_english_programmatically.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,10 @@

def loadDictionary():
path = os.path.split(os.path.realpath(__file__))
dictionaryFile = open(path[0] + '/Dictionary.txt')
englishWords = {}
for word in dictionaryFile.read().split('\n'):
englishWords[word] = None
dictionaryFile.close()
with open(path[0] + '/Dictionary.txt') as dictionaryFile:
for word in dictionaryFile.read().split('\n'):
englishWords[word] = None
return englishWords

ENGLISH_WORDS = loadDictionary()
Expand Down
34 changes: 16 additions & 18 deletions searches/tabu_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,24 +45,23 @@ def generate_neighbours(path):
the node 'c' with distance 18, the node 'd' with distance 22 and the node 'e' with distance 26.
"""
f = open(path, "r")

dict_of_neighbours = {}

for line in f:
if line.split()[0] not in dict_of_neighbours:
_list = list()
_list.append([line.split()[1], line.split()[2]])
dict_of_neighbours[line.split()[0]] = _list
else:
dict_of_neighbours[line.split()[0]].append([line.split()[1], line.split()[2]])
if line.split()[1] not in dict_of_neighbours:
_list = list()
_list.append([line.split()[0], line.split()[2]])
dict_of_neighbours[line.split()[1]] = _list
else:
dict_of_neighbours[line.split()[1]].append([line.split()[0], line.split()[2]])
f.close()
with open(path) as f:
for line in f:
if line.split()[0] not in dict_of_neighbours:
_list = list()
_list.append([line.split()[1], line.split()[2]])
dict_of_neighbours[line.split()[0]] = _list
else:
dict_of_neighbours[line.split()[0]].append([line.split()[1], line.split()[2]])
if line.split()[1] not in dict_of_neighbours:
_list = list()
_list.append([line.split()[0], line.split()[2]])
dict_of_neighbours[line.split()[1]] = _list
else:
dict_of_neighbours[line.split()[1]].append([line.split()[0], line.split()[2]])

return dict_of_neighbours

Expand All @@ -84,16 +83,15 @@ def generate_first_solution(path, dict_of_neighbours):
"""

f = open(path, "r")
start_node = f.read(1)
with open(path) as f:
start_node = f.read(1)
end_node = start_node

first_solution = []

visiting = start_node

distance_of_first_solution = 0
f.close()
while visiting not in first_solution:
minim = 10000
for k in dict_of_neighbours[visiting]:
Expand Down
38 changes: 18 additions & 20 deletions sorts/external-sort.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,31 +15,29 @@ def __init__(self, filename):

def write_block(self, data, block_number):
filename = self.BLOCK_FILENAME_FORMAT.format(block_number)
file = open(filename, 'w')
file.write(data)
file.close()
with open(filename, 'w') as file:
file.write(data)
self.block_filenames.append(filename)

def get_block_filenames(self):
return self.block_filenames

def split(self, block_size, sort_key=None):
file = open(self.filename, 'r')
i = 0
with open(self.filename) as file:
while True:
lines = file.readlines(block_size)

while True:
lines = file.readlines(block_size)
if lines == []:
break

if lines == []:
break
if sort_key is None:
lines.sort()
else:
lines.sort(key=sort_key)

if sort_key is None:
lines.sort()
else:
lines.sort(key=sort_key)

self.write_block(''.join(lines), i)
i += 1
self.write_block(''.join(lines), i)
i += 1

def cleanup(self):
map(lambda f: os.remove(f), self.block_filenames)
Expand Down Expand Up @@ -74,6 +72,7 @@ def refresh(self):

if self.buffers[i] == '':
self.empty.add(i)
self.files[i].close()

if len(self.empty) == self.num_buffers:
return False
Expand All @@ -92,12 +91,11 @@ def __init__(self, merge_strategy):
self.merge_strategy = merge_strategy

def merge(self, filenames, outfilename, buffer_size):
outfile = open(outfilename, 'w', buffer_size)
buffers = FilesArray(self.get_file_handles(filenames, buffer_size))

while buffers.refresh():
min_index = self.merge_strategy.select(buffers.get_dict())
outfile.write(buffers.unshift(min_index))
with open(outfilename, 'w', buffer_size) as outfile:
while buffers.refresh():
min_index = self.merge_strategy.select(buffers.get_dict())
outfile.write(buffers.unshift(min_index))

def get_file_handles(self, filenames, buffer_size):
files = {}
Expand Down
79 changes: 39 additions & 40 deletions strings/min_cost_string_conversion.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,50 +73,49 @@ def assemble_transformation(ops, i, j):
m = len(operations)
n = len(operations[0])
sequence = assemble_transformation(operations, m-1, n-1)

file = open('min_cost.txt', 'w')

string = list('Python')
i = 0
cost = 0
for op in sequence:
print(''.join(string))

if op[0] == 'C':
file.write('%-16s' % 'Copy %c' % op[1])
file.write('\t\t\t' + ''.join(string))
file.write('\r\n')

cost -= 1
elif op[0] == 'R':
string[i] = op[2]

file.write('%-16s' % ('Replace %c' % op[1] + ' with ' + str(op[2])))
file.write('\t\t' + ''.join(string))
file.write('\r\n')

cost += 1
elif op[0] == 'D':
string.pop(i)

file.write('%-16s' % 'Delete %c' % op[1])
file.write('\t\t\t' + ''.join(string))
file.write('\r\n')

cost += 2
else:
string.insert(i, op[1])

with open('min_cost.txt', 'w') as file:
for op in sequence:
print(''.join(string))

if op[0] == 'C':
file.write('%-16s' % 'Copy %c' % op[1])
file.write('\t\t\t' + ''.join(string))
file.write('\r\n')

cost -= 1
elif op[0] == 'R':
string[i] = op[2]

file.write('%-16s' % ('Replace %c' % op[1] + ' with ' + str(op[2])))
file.write('\t\t' + ''.join(string))
file.write('\r\n')

cost += 1
elif op[0] == 'D':
string.pop(i)

file.write('%-16s' % 'Delete %c' % op[1])
file.write('\t\t\t' + ''.join(string))
file.write('\r\n')

cost += 2
else:
string.insert(i, op[1])

file.write('%-16s' % 'Insert %c' % op[1])
file.write('\t\t\t' + ''.join(string))
file.write('\r\n')

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

i += 1
i += 1

print(''.join(string))
print('Cost: ', cost)

file.write('\r\nMinimum cost: ' + str(cost))
file.close()
print(''.join(string))
print('Cost: ', cost)

file.write('\r\nMinimum cost: ' + str(cost))

0 comments on commit 2d70e9f

Please sign in to comment.