首页 > 解决方案 > 字符串比较不起作用!语言是python

问题描述

import hashlib
import os

dir_path = input("Input directory : ") + "/"
hashset_path = input("Input hashset directory (ex: C:/../user/hashset.txt) : ")
hash_type = int(input("1:MD5 2.SHA-1 3.SHA-256\n choose hash : "))

if hash_type == 1:
    hash_type = "md5"
elif hash_type == 2:
    hash_type = "sha1"
elif hash_type == 3:
    hash_type = "sha256"
else:
    print("somethig is wrong")
    exit()

temp = getattr(hashlib, hash_type)


f1 = open(hashset_path,'r',encoding='UTF-8')
lines = f1.readlines()

for line in lines:
    line = line.strip()  
f1.close()


# compare file
file_lst = os.listdir(dir_path)
count = 0
matchedfile = []
for file in file_lst:
    filepath = dir_path + file

    f = open(filepath, 'rb')
    data = f.read()
    f.close()

    for n in range(0,len(lines)):
        if (str(temp(data).hexdigest()) == str(lines[n])): 
            matchedfile.append("filename : " + file + " " + "calculated hash : " + temp(data).hexdigest() + " " + "hash of hashset.txt : " + lines[n])
            count += 1


if count == 0:
    print("no matched hash")
else:
    for i in range(0,len(matchedfile)):
        print(matchedfile[i])

我的代码有什么问题? if (str(temp(data).hexdigest()) == str(lines[n])): 此代码不起作用..甚至两个字符串都完全相同!我能怎么做..

标签: pythonlistcompare

解决方案


您似乎正在从文本文件中读取。请注意,此过程包括您实际上并未剥离的行尾:

for line in lines:
    line = line.strip()

上面的代码片段除了浪费时间之外什么也没做。

你的意思是这样写:

lines = [line.strip() for line in lines]

推荐阅读