diff --git a/ciphers/rsa_cipher.py b/ciphers/rsa_cipher.py index 3f8fb96e1..d81f1ffc1 100644 --- a/ciphers/rsa_cipher.py +++ b/ciphers/rsa_cipher.py @@ -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) diff --git a/ciphers/transposition_cipher_encrypt_decrypt_file.py b/ciphers/transposition_cipher_encrypt_decrypt_file.py index 57620d839..a186cf81c 100644 --- a/ciphers/transposition_cipher_encrypt_decrypt_file.py +++ b/ciphers/transposition_cipher_encrypt_decrypt_file.py @@ -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 )')) diff --git a/file_transfer_protocol/ftp_client_server.py b/file_transfer_protocol/ftp_client_server.py index f73f85843..414c336de 100644 --- a/file_transfer_protocol/ftp_client_server.py +++ b/file_transfer_protocol/ftp_client_server.py @@ -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') diff --git a/file_transfer_protocol/ftp_send_receive.py b/file_transfer_protocol/ftp_send_receive.py index d4919158a..6050c83f2 100644 --- a/file_transfer_protocol/ftp_send_receive.py +++ b/file_transfer_protocol/ftp_send_receive.py @@ -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() diff --git a/hashes/sha1.py b/hashes/sha1.py index e34f87a76..4c78ad3a8 100644 --- a/hashes/sha1.py +++ b/hashes/sha1.py @@ -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()) diff --git a/other/anagrams.py b/other/anagrams.py index 44cd96b75..29b34fbdc 100644 --- a/other/anagrams.py +++ b/other/anagrams.py @@ -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)) diff --git a/other/detecting_english_programmatically.py b/other/detecting_english_programmatically.py index 305174e31..005fd3c10 100644 --- a/other/detecting_english_programmatically.py +++ b/other/detecting_english_programmatically.py @@ -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() diff --git a/searches/tabu_search.py b/searches/tabu_search.py index 74c23f8b8..e21ddd53c 100644 --- a/searches/tabu_search.py +++ b/searches/tabu_search.py @@ -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]: diff --git a/sorts/external-sort.py b/sorts/external-sort.py index dece32d48..1638e9efa 100644 --- a/sorts/external-sort.py +++ b/sorts/external-sort.py @@ -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 = {} diff --git a/strings/min_cost_string_conversion.py b/strings/min_cost_string_conversion.py index c233af1c8..de7f9f727 100644 --- a/strings/min_cost_string_conversion.py +++ b/strings/min_cost_string_conversion.py @@ -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))