Skip to main content
 首页 » 编程设计

python之在 python 中使用 pydoop 保存 gzip 文件

2024年10月01日38rubylouvre

我正在使用 pydoop 在 pyspark 中读取和写入文件。我想以 gzip 格式编写作业输出。我当前的代码如下所示:

def create_data_distributed(workerNum,outputDir, centers, noSamples = 10, var = 0.1): 
numCenters = centers.shape[0] 
dim = centers.shape[1] 
fptr_out = hdfs.hdfs().open_file(os.path.join(outputDir, ("part-%05d" % workerNum) ) + ".txt", "w") 
for idx in range(noSamples): 
    idxCenter = np.random.randint(numCenters) 
    sample = centers[idxCenter] + np.random.normal(size=(1,dim)) 
    # output the sample. Need to  
    fptr_out.write("%d, " % idxCenter) 
    for i in range(len(sample[0])): 
        fptr_out.write("%f " %(sample[0][i])) 
        if (i < (len(sample[0])-1)): 
            fptr_out.write(",") 
    fptr_out.write("\n") 
fptr_out.close() 
return 

如何使此代码打开和写入 gzip 文件而不是常规文件?

谢谢!!!

请您参考如下方法:

我希望您可以通过包装返回的类文件对象来做到这一点:

fptr_out = hdfs.hdfs().open_file(...) 

与 gzip.GzipFile喜欢:

hdfs_file = hdfs.hdfs().open_file(...) 
fptr_out = gzip.GzipFile(mode='wb', fileobj=hdfs_file) 

请注意,您必须对两者都调用 close:

fptr_out.close() 
hdfs_file.close() 

with 语句更清楚:

output_filename = os.path.join(outputDir, ("part-%05d" % workerNum) ) + ".txt.gz" 
with hdfs.hdfs().open_file(output_filename, "wb") as hdfs_file: 
    with gzip.GzipFile(mode='wb', fileobj=hdfs_file) as fptr_out: 
         ... 

这一切都未经测试。使用风险自负。