在Python中使用pydoop儲存gzip檔案

2024-04-23 07:13:50 发布

您现在位置:Python中文网/ 问答频道 /正文

用pydoop来读写文件。我想用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文件而不是普通文件?在

谢谢!!!在


Tags: 文件sample代码outwriteoutputdirshapedim
1条回答
网友
1楼 · 发布于 2024-04-23 07:13:50

我希望您可以通过包装返回的类似文件的对象来完成此操作:

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

^{}类似:

^{pr2}$

请注意,您必须同时调用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:
         ...

这些都是未经测试的。使用风险自负。在

相关问题 更多 >