如何将值仅哈希到" ="签名(或任何其他分隔符)并输出新的文本文件

时间:2015-01-07 18:00:11

标签: python-3.x hashlib

我根据csv文件的用户输入以特定格式输出了一个文本文件(在用户建议的帮助下)。现在我想只将值散列到“=”符号的右边,并输出具有相同格式但散列值为右的新文本文件。这里是代码向我建议的一些我的mods,适用于第一部分:

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

我可以使用以下代码散列整行:

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)

但无法弄清楚如何分割线 - 例如“Full_Name = Jack Flash”只获取“Jack Flash”作为要散列的对象;散列“Jack Flash”并将值写入新文本文件key =哈希值的格式。以上代码保存到csv文件。我正在剪切和粘贴相关部分,所以希望这是有道理的。有关如何实现这一目标的任何想法?提前谢谢!

1 个答案:

答案 0 :(得分:0)

您正在寻找的是str.split(' =')

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

如果你不想要最初的' '哈希,删除它。或者,如果' ='总是'其次是' ',。split(' =')。