【问题标题】:Generating file hashes through pandas dataframe apply creates the same hash for all files通过 pandas 数据框应用生成文件哈希会为所有文件创建相同的哈希
【发布时间】:2020-09-05 09:32:08
【问题描述】:

如果有一个充满文件路径的数据框,我想为每个文件创建哈希

代码如下所示:

def generate_hash(path):
    path = paht['path']
    BLOCK_SIZE = 10485760 
    file_hash = hashlib.sha256() 
    with open(file, 'rb') as f: 
        fb = f.read(BLOCK_SIZE) 
        while len(fb) > 0: 
            file_hash.update(fb) 
            fb = f.read(BLOCK_SIZE) 

    return file_hash.hexdigest() 


df['hash'] = df.apply((generate_hash, axis=1)

这样会为每个文件生成相同的哈希值,df 看起来像这样:

   path           hash
0  /path/file_1   09b85c3f91d4fc5fe88610acad1094d064b253ebfacf26ed2cb16c4e89468504
1  /path/file_2   09b85c3f91d4fc5fe88610acad1094d064b253ebfacf26ed2cb16c4e89468504  
2  /path/file_3   09b85c3f91d4fc5fe88610acad1094d064b253ebfacf26ed2cb16c4e89468504
3  /path/file_4   09b85c3f91d4fc5fe88610acad1094d064b253ebfacf26ed2cb16c4e89468504  
4  /path/file_5   09b85c3f91d4fc5fe88610acad1094d064b253ebfacf26ed2cb16c4e89468504  

但由于它们是不同的文件,它们不应该生成相同的哈希值,当我只是迭代 for loop 中的路径时正确生成的哈希值

这段代码:

for file in glob.glob('path/**', recursive=True):
    print(file)
    print(generate_hash(file))

产生预期的结果:

/path/file_1  
fdf755afcb1a4a38474ab1f2bca4969eec6e3dac09772559f473c33915b1323d
/path/file_2
957c584f39d2a8938174a9b715b9d67998ebb7ba94619f15e076a5c649714067
/path/file_3 
fab912b026cbd2ba4c507ffa6f996e862133e1db2c705881819fa258eb76bebc
/path/file_4 
d7dc9e575e4e36ed5542e9102044926598b0a600e1e0f59db3993be53518b7e6
/path/file_5
09b85c3f91d4fc5fe88610acad1094d064b253ebfacf26ed2cb16c4e89468504

所以在 df 示例中,每一行都得到 file_5 的实际哈希值,我在这里缺少什么?pn

【问题讨论】:

    标签: python pandas hash


    【解决方案1】:

    您必须将open(file, 'rb') 替换为open(path, 'rb'),这里path 表示当前系列s 中传递给generate_hash 函数的path 的值。

    用途:

    def generate_hash(s):
        path = s['path']
        BLOCK_SIZE = 10485760 
        file_hash = hashlib.sha256() 
        with open(path, 'rb') as f: 
            fb = f.read(BLOCK_SIZE) 
            while len(fb) > 0: 
                file_hash.update(fb) 
                fb = f.read(BLOCK_SIZE) 
    
        return file_hash.hexdigest() 
    

    【讨论】:

      猜你喜欢
      • 2012-11-19
      • 1970-01-01
      • 2016-07-16
      • 1970-01-01
      • 2019-04-28
      • 2023-03-17
      • 1970-01-01
      • 2021-11-10
      • 1970-01-01
      相关资源
      最近更新 更多