-1

i outputted a text file based on user input from csv file, in certain format (with help from user suggestions). Now i want to hash only value to right of "=" sign and output new text file with same format but hashed values to right. here is code suggested to me with some of my mods, that worked for the 1st part:

import csv

device = input("Enter the device name: ").upper()

output_file = 'C:\path_to_scripts\{}_items.txt'.format(device)

with open(r'C:\path_to_script\filename_Brief.csv') as infh, \
    open(output_file, 'wt') as outfh:
    reader = csv.DictReader(infh)
    for row in reader:
        if row['ALIAS'] == device:
             outfh.write('Full_Name = {Full_Name}\n'
                         'PHONE_NO = {PHONE_NO}\n'
                         'ALIAS = {ALIAS}\n'.format(**row))

I can hash the whole line using code such as:

import hashlib

with open(outfh, 'r') as file:

    lines = [x.strip('\n') for x in file.readlines()]
    hashfile = 'C:\path_to_scripts\{}_hashed.csv'.format(device)
    with open(hash_file,'w') as save_file:


        # Write the saved file header
        header = '\"Value\",\"Algorithm\",\"Hash\"\n'
        save_file.write(header)

        # For each line in file
        for line in lines:
            # Create a list of all the available algorithms
            algorithms = ['md5','sha1','sha224','sha256','sha384','sha512']

            # For each algorithm
            for algo in algorithms:

                # Encode the original value as utf8
                val_enc = line.encode('utf-8')

                # Create the hashing object using the current algorithm
                hashed = hashlib.new(algo)

                # Set the value we want the hash of
                hashed.update(val_enc)

                # Get the hash
                hash_digest = hashed.hexdigest()


                results = '\"{}\",\"{}\",\"{}\"\n'.format(line, algo, hash_digest)
                save_file.write(results)

but can't figure out how to split the line--for example "Full_Name = Jack Flash" to obtain only "Jack Flash" as object to be hashed;hash "Jack Flash" and write values to new text file with format of key = hashed value. The above code saves to a csv file. i am cutting and pasting relevant sections so hope that makes sense. Any ideas on how to accomplish this? thanks in advance!

tmdb
  • 1
  • 2

1 Answers1

0

What you are looking for is str.split('=')

>>> line =  "Full_Name = Jack Flash"
>>> parts = line.split('=')
>>> parts
['Full_Name ', ' Jack Flash']
>>> parts[1]
' Jack Flash'

If you do not want the initial ' ' hashed, remove it. Or, if '=' is *always' followed by ' ', .split('= ').

Terry Jan Reedy
  • 18,414
  • 3
  • 40
  • 52