-1

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

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”并将值写入具有键格式的新文本文件= 哈希值。上面的代码保存到一个 csv 文件中。我正在剪切和粘贴相关部分,所以希望这是有道理的。关于如何做到这一点的任何想法?提前致谢!

4

1 回答 1

0

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

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

如果您不希望初始 ' ' 散列,请将其删除。或者,如果 '=' 是 *always' 后跟 ' ',则 .split('= ')。

于 2015-01-07T23:17:39.543 回答