gpt4 book ai didi

python - 获取子目录列表

转载 作者:可可西里 更新时间:2023-11-01 16:42:33 24 4
gpt4 key购买 nike

我知道我可以做到:

data = sc.textFile('/hadoop_foo/a')
data.count()
240
data = sc.textFile('/hadoop_foo/*')
data.count()
168129

但是,我想统计“/hadoop_foo/”的每个子目录的数据大小。我可以这样做吗?

换句话说,我想要的是这样的:

subdirectories = magicFunction()
for subdir in subdirectories:
data sc.textFile(subdir)
data.count()

我试过:

In [9]: [x[0] for x in os.walk("/hadoop_foo/")]
Out[9]: []

但我认为失败了,因为它在驱动程序的本地目录(在这种情况下是网关)中搜索,而“/hadoop_foo/”位于 中.与“hdfs:///hadoop_foo/”相同。


看完How can I list subdirectories recursively for HDFS? ,我想知道有没有办法执行:

hadoop dfs -lsr /hadoop_foo/

在代码中..


来自 Correct way of writing two floats into a regular txt :

In [28]: os.getcwd()
Out[28]: '/homes/gsamaras' <-- which is my local directory

最佳答案

用 python 使用 hdfs模块; walk()方法可以获得文件列表。

代码看起来像这样:

from hdfs import InsecureClient

client = InsecureClient('http://host:port', user='user')
for stuff in client.walk(dir, 0, True):
...

使用 Scala,您可以获得文件系统 (val fs = FileSystem.get(new Configuration())) 并运行 https://hadoop.apache.org/docs/r2.4.1/api/org/apache/hadoop/fs/FileSystem.html#listFiles(org.apache.hadoop.fs.Path , bool 值)

您还可以使用 os.subprocess 从脚本中执行 shell 命令但这绝不是推荐的方法,因为您在这里依赖于 shell 实用程序的文本输出。


最终,对 OP 有用的是使用 subprocess.check_output() :

subdirectories = subprocess.check_output(["hadoop","fs","-ls", "/hadoop_foo/"])

关于python - 获取子目录列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39420685/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com