Fix ResourceWarning: unclosed file (#681)

Signed-off-by: Mickaël Schoentgen <contact@tiger-222.fr>
This commit is contained in:
Mickaël Schoentgen 2019-01-08 09:59:23 +01:00 committed by Libin Yang
parent 3dc50529ca
commit 2d70e9f747
10 changed files with 104 additions and 110 deletions

View File

@ -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))
@ -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)

View File

@ -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 )'))

View File

@ -17,13 +17,12 @@ while True:
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')

View File

@ -20,10 +20,9 @@ ftp.cwd('/Enter the directory here/')
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
@ -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()

View File

@ -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())

View File

@ -4,7 +4,8 @@ import collections, pprint, time, os
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))

View File

@ -5,11 +5,10 @@ LETTERS_AND_SPACE = UPPERLETTERS + UPPERLETTERS.lower() + ' \t\n'
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()

View File

@ -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
@ -84,8 +83,8 @@ 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 = []
@ -93,7 +92,6 @@ def generate_first_solution(path, dict_of_neighbours):
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]:

View File

@ -15,31 +15,29 @@ class FileSplitter(object):
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)
@ -74,6 +72,7 @@ class FilesArray(object):
if self.buffers[i] == '':
self.empty.add(i)
self.files[i].close()
if len(self.empty) == self.num_buffers:
return False
@ -92,12 +91,11 @@ class FileMerger(object):
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 = {}

View File

@ -73,50 +73,49 @@ if __name__ == '__main__':
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])
file.write('%-16s' % 'Insert %c' % op[1])
file.write('\t\t\t' + ''.join(string))
file.write('\r\n')
cost += 2
i += 1
print(''.join(string))
print('Cost: ', cost)
file.write('\r\nMinimum cost: ' + str(cost))
file.close()
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
i += 1
print(''.join(string))
print('Cost: ', cost)
file.write('\r\nMinimum cost: ' + str(cost))