计算文件哈希/校验和的代码不起作用 [英] Pyspark - Code to calculate file hash/checksum not working
本文介绍了计算文件哈希/校验和的代码不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
pyspark
代码来计算文件夹中每个文件的SHA1散列。我使用spark.sparkContext.binaryFiles
来获取RDD对,其中键是文件名,值是一个类似文件的对象,我正在计算映射函数rdd.mapValues(map_hash_file)
中的散列。然而,我在倒数第二行收到了下面的错误,我不明白--请问如何解决这个问题?谢谢
错误:
org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 66.0 failed 4 times, most recent failure: Lost task 0.3 in stage 66.0
编码:
#Function to calulcate hash-value/checksum of a file
def map_hash_file(row):
file_name = row[0]
file_contents = row[1]
sha1_hash = hashlib.sha1()
sha1_hash.update(file_contents.encode('utf-8'))
return file_name, sha1_hash.hexdigest()
rdd = spark.sparkContext.binaryFiles('/mnt/workspace/Test_Folder', minPartitions=None)
#As a check, print the list of files collected in the RDD
dataColl=rdd.collect()
for row in dataColl:
print(row[0])
#Apply the function to calcuate hash of each file and store the results
hash_values = rdd.mapValues(map_hash_file)
#Store each file name and it's hash value in a dataframe to later export as a CSV
df = spark.createDataFrame(data=hash_values)
display(df)
推荐答案
如果执行以下操作,您将获得预期的结果:
- 将
file_contents.encode('utf-8')
更改为file_contents
。file_contents
已是类型bytes
- 将
rdd.mapValues(map_hash_file)
更改为rdd.map(map_hash_file)
。函数map_hash_file
需要一个元组。
还要考虑:
- 添加
import hashlib
- 如果不将所有文件的内容收集到驱动程序,可能会消耗驱动程序上的所有内存。
进行上述更改后,您的代码应该如下所示:
import hashlib
#Function to calulcate hash-value/checksum of a file
def map_hash_file(row):
file_name = row[0]
file_contents = row[1]
sha1_hash = hashlib.sha1()
sha1_hash.update(file_contents)
return file_name, sha1_hash.hexdigest()
rdd = spark.sparkContext.binaryFiles('/mnt/workspace/Test_Folder', minPartitions=None)
#Apply the function to calcuate hash of each file and store the results
hash_values = rdd.map(map_hash_file)
#Store each file name and it's hash value in a dataframe to later export as a CSV
df = spark.createDataFrame(data=hash_values)
display(df)
这篇关于计算文件哈希/校验和的代码不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文