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)
with open(keyFilename) as fo:
content = fo.read()
fo.close()
keySize, n, EorD = content.split(',')
return (int(keySize), int(n), int(EorD))
@ -98,15 +97,14 @@ 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')
with open(messageFilename, 'w') as fo:
fo.write(encryptedContent)
fo.close()
return encryptedContent
def readFromFileAndDecrypt(messageFilename, keyFilename):
keySize, n, d = readKeyFile(keyFilename)
fo = open(messageFilename)
with open(messageFilename) as fo:
content = fo.read()
messageLength, blockSize, encryptedMessage = content.split('_')
messageLength = int(messageLength)

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')
with open(outputFile, 'w') as outputObj:
outputObj.write(translated)
outputObj.close()
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')
with open(filename, 'rb') as f:
in_data = f.read(1024)
while (in_data):
while in_data:
conn.send(in_data)
print('Sent ', repr(in_data))
in_data = f.read(1024)
f.close()
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')
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 = {}
with open(path[0] + '/Dictionary.txt') as dictionaryFile:
for word in dictionaryFile.read().split('\n'):
englishWords[word] = None
dictionaryFile.close()
return englishWords
ENGLISH_WORDS = loadDictionary()

View File

@ -45,10 +45,10 @@ 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 = {}
with open(path) as f:
for line in f:
if line.split()[0] not in dict_of_neighbours:
_list = list()
@ -62,7 +62,6 @@ def generate_neighbours(path):
dict_of_neighbours[line.split()[1]] = _list
else:
dict_of_neighbours[line.split()[1]].append([line.split()[0], line.split()[2]])
f.close()
return dict_of_neighbours
@ -84,7 +83,7 @@ def generate_first_solution(path, dict_of_neighbours):
"""
f = open(path, "r")
with open(path) as f:
start_node = f.read(1)
end_node = start_node
@ -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,18 +15,16 @@ class FileSplitter(object):
def write_block(self, data, block_number):
filename = self.BLOCK_FILENAME_FORMAT.format(block_number)
file = open(filename, 'w')
with open(filename, 'w') as file:
file.write(data)
file.close()
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)
@ -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,9 +91,8 @@ 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))
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))

View File

@ -74,11 +74,11 @@ if __name__ == '__main__':
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
with open('min_cost.txt', 'w') as file:
for op in sequence:
print(''.join(string))
@ -119,4 +119,3 @@ if __name__ == '__main__':
print('Cost: ', cost)
file.write('\r\nMinimum cost: ' + str(cost))
file.close()