-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 に答える