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): def readKeyFile(keyFilename):
fo = open(keyFilename) with open(keyFilename) as fo:
content = fo.read() content = fo.read()
fo.close()
keySize, n, EorD = content.split(',') keySize, n, EorD = content.split(',')
return (int(keySize), int(n), int(EorD)) return (int(keySize), int(n), int(EorD))
@ -98,16 +97,15 @@ def encryptAndWriteToFile(messageFilename, keyFilename, message, blockSize=DEFAU
encryptedBlocks[i] = str(encryptedBlocks[i]) encryptedBlocks[i] = str(encryptedBlocks[i])
encryptedContent = ','.join(encryptedBlocks) encryptedContent = ','.join(encryptedBlocks)
encryptedContent = '%s_%s_%s' % (len(message), blockSize, encryptedContent) encryptedContent = '%s_%s_%s' % (len(message), blockSize, encryptedContent)
fo = open(messageFilename, 'w') with open(messageFilename, 'w') as fo:
fo.write(encryptedContent) fo.write(encryptedContent)
fo.close()
return encryptedContent return encryptedContent
def readFromFileAndDecrypt(messageFilename, keyFilename): def readFromFileAndDecrypt(messageFilename, keyFilename):
keySize, n, d = readKeyFile(keyFilename) keySize, n, d = readKeyFile(keyFilename)
fo = open(messageFilename) with open(messageFilename) as fo:
content = fo.read() content = fo.read()
messageLength, blockSize, encryptedMessage = content.split('_') messageLength, blockSize, encryptedMessage = content.split('_')
messageLength = int(messageLength) messageLength = int(messageLength)
blockSize = int(blockSize) blockSize = int(blockSize)

View File

@ -19,15 +19,16 @@ def main():
startTime = time.time() startTime = time.time()
if mode.lower().startswith('e'): if mode.lower().startswith('e'):
content = open(inputFile).read() with open(inputFile) as f:
content = f.read()
translated = transCipher.encryptMessage(key, content) translated = transCipher.encryptMessage(key, content)
elif mode.lower().startswith('d'): elif mode.lower().startswith('d'):
content = open(outputFile).read() with open(outputFile) as f:
content = f.read()
translated =transCipher .decryptMessage(key, content) translated =transCipher .decryptMessage(key, content)
outputObj = open(outputFile, 'w') with open(outputFile, 'w') as outputObj:
outputObj.write(translated) outputObj.write(translated)
outputObj.close()
totalTime = round(time.time() - startTime, 2) totalTime = round(time.time() - startTime, 2)
print(('Done (', totalTime, 'seconds )')) print(('Done (', totalTime, 'seconds )'))

View File

@ -17,13 +17,12 @@ while True:
print('Server received', repr(data)) print('Server received', repr(data))
filename = 'mytext.txt' filename = 'mytext.txt'
f = open(filename, 'rb') with open(filename, 'rb') as f:
in_data = f.read(1024) in_data = f.read(1024)
while (in_data): while in_data:
conn.send(in_data) conn.send(in_data)
print('Sent ', repr(in_data)) print('Sent ', repr(in_data))
in_data = f.read(1024) in_data = f.read(1024)
f.close()
print('Done sending') print('Done sending')
conn.send('Thank you for connecting') conn.send('Thank you for connecting')

View File

@ -20,10 +20,9 @@ ftp.cwd('/Enter the directory here/')
def ReceiveFile(): def ReceiveFile():
FileName = 'example.txt' """ Enter the location of the file """ FileName = 'example.txt' """ Enter the location of the file """
LocalFile = open(FileName, 'wb') with open(FileName, 'wb') as LocalFile:
ftp.retrbinary('RETR ' + FileName, LocalFile.write, 1024) ftp.retrbinary('RETR ' + FileName, LocalFile.write, 1024)
ftp.quit() ftp.quit()
LocalFile.close()
""" """
The file which will be sent via the FTP server The file which will be sent via the FTP server
@ -32,5 +31,6 @@ def ReceiveFile():
def SendFile(): def SendFile():
FileName = 'example.txt' """ Enter the name of the file """ 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() ftp.quit()

View File

@ -137,7 +137,8 @@ def main():
input_string = args.input_string input_string = args.input_string
#In any case hash input should be a bytestring #In any case hash input should be a bytestring
if args.input_file: 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: else:
hash_input = bytes(input_string, 'utf-8') hash_input = bytes(input_string, 'utf-8')
print(SHA1Hash(hash_input).final_hash()) print(SHA1Hash(hash_input).final_hash())

View File

@ -4,7 +4,8 @@ import collections, pprint, time, os
start_time = time.time() start_time = time.time()
print('creating word list...') print('creating word list...')
path = os.path.split(os.path.realpath(__file__)) 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): def signature(word):
return ''.join(sorted(word)) return ''.join(sorted(word))

View File

@ -5,11 +5,10 @@ LETTERS_AND_SPACE = UPPERLETTERS + UPPERLETTERS.lower() + ' \t\n'
def loadDictionary(): def loadDictionary():
path = os.path.split(os.path.realpath(__file__)) path = os.path.split(os.path.realpath(__file__))
dictionaryFile = open(path[0] + '/Dictionary.txt')
englishWords = {} englishWords = {}
for word in dictionaryFile.read().split('\n'): with open(path[0] + '/Dictionary.txt') as dictionaryFile:
englishWords[word] = None for word in dictionaryFile.read().split('\n'):
dictionaryFile.close() englishWords[word] = None
return englishWords return englishWords
ENGLISH_WORDS = loadDictionary() 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. 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 = {} dict_of_neighbours = {}
for line in f: with open(path) as f:
if line.split()[0] not in dict_of_neighbours: for line in f:
_list = list() if line.split()[0] not in dict_of_neighbours:
_list.append([line.split()[1], line.split()[2]]) _list = list()
dict_of_neighbours[line.split()[0]] = _list _list.append([line.split()[1], line.split()[2]])
else: dict_of_neighbours[line.split()[0]] = _list
dict_of_neighbours[line.split()[0]].append([line.split()[1], line.split()[2]]) else:
if line.split()[1] not in dict_of_neighbours: dict_of_neighbours[line.split()[0]].append([line.split()[1], line.split()[2]])
_list = list() if line.split()[1] not in dict_of_neighbours:
_list.append([line.split()[0], line.split()[2]]) _list = list()
dict_of_neighbours[line.split()[1]] = _list _list.append([line.split()[0], line.split()[2]])
else: dict_of_neighbours[line.split()[1]] = _list
dict_of_neighbours[line.split()[1]].append([line.split()[0], line.split()[2]]) else:
f.close() dict_of_neighbours[line.split()[1]].append([line.split()[0], line.split()[2]])
return dict_of_neighbours return dict_of_neighbours
@ -84,8 +83,8 @@ def generate_first_solution(path, dict_of_neighbours):
""" """
f = open(path, "r") with open(path) as f:
start_node = f.read(1) start_node = f.read(1)
end_node = start_node end_node = start_node
first_solution = [] first_solution = []
@ -93,7 +92,6 @@ def generate_first_solution(path, dict_of_neighbours):
visiting = start_node visiting = start_node
distance_of_first_solution = 0 distance_of_first_solution = 0
f.close()
while visiting not in first_solution: while visiting not in first_solution:
minim = 10000 minim = 10000
for k in dict_of_neighbours[visiting]: for k in dict_of_neighbours[visiting]:

View File

@ -15,31 +15,29 @@ class FileSplitter(object):
def write_block(self, data, block_number): def write_block(self, data, block_number):
filename = self.BLOCK_FILENAME_FORMAT.format(block_number) filename = self.BLOCK_FILENAME_FORMAT.format(block_number)
file = open(filename, 'w') with open(filename, 'w') as file:
file.write(data) file.write(data)
file.close()
self.block_filenames.append(filename) self.block_filenames.append(filename)
def get_block_filenames(self): def get_block_filenames(self):
return self.block_filenames return self.block_filenames
def split(self, block_size, sort_key=None): def split(self, block_size, sort_key=None):
file = open(self.filename, 'r')
i = 0 i = 0
with open(self.filename) as file:
while True:
lines = file.readlines(block_size)
while True: if lines == []:
lines = file.readlines(block_size) break
if lines == []: if sort_key is None:
break lines.sort()
else:
lines.sort(key=sort_key)
if sort_key is None: self.write_block(''.join(lines), i)
lines.sort() i += 1
else:
lines.sort(key=sort_key)
self.write_block(''.join(lines), i)
i += 1
def cleanup(self): def cleanup(self):
map(lambda f: os.remove(f), self.block_filenames) map(lambda f: os.remove(f), self.block_filenames)
@ -74,6 +72,7 @@ class FilesArray(object):
if self.buffers[i] == '': if self.buffers[i] == '':
self.empty.add(i) self.empty.add(i)
self.files[i].close()
if len(self.empty) == self.num_buffers: if len(self.empty) == self.num_buffers:
return False return False
@ -92,12 +91,11 @@ class FileMerger(object):
self.merge_strategy = merge_strategy self.merge_strategy = merge_strategy
def merge(self, filenames, outfilename, buffer_size): def merge(self, filenames, outfilename, buffer_size):
outfile = open(outfilename, 'w', buffer_size)
buffers = FilesArray(self.get_file_handles(filenames, buffer_size)) buffers = FilesArray(self.get_file_handles(filenames, buffer_size))
with open(outfilename, 'w', buffer_size) as outfile:
while buffers.refresh(): while buffers.refresh():
min_index = self.merge_strategy.select(buffers.get_dict()) min_index = self.merge_strategy.select(buffers.get_dict())
outfile.write(buffers.unshift(min_index)) outfile.write(buffers.unshift(min_index))
def get_file_handles(self, filenames, buffer_size): def get_file_handles(self, filenames, buffer_size):
files = {} files = {}

View File

@ -73,50 +73,49 @@ if __name__ == '__main__':
m = len(operations) m = len(operations)
n = len(operations[0]) n = len(operations[0])
sequence = assemble_transformation(operations, m-1, n-1) sequence = assemble_transformation(operations, m-1, n-1)
file = open('min_cost.txt', 'w')
string = list('Python') string = list('Python')
i = 0 i = 0
cost = 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)) with open('min_cost.txt', 'w') as file:
file.close() 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))