【问题标题】:Extract the names of files from HDFS using Python使用 Python 从 HDFS 中提取文件名
【发布时间】:2018-08-02 02:22:12
【问题描述】:

我正在使用 Python,我需要直接通过 python 获取我在文件夹(另存为 HDFS)中的文件名列表,并将文件名(即 .wav 文件)与其路径(我只需要名字)。我在想可能是我可以使用 pyspark 或子进程,但它们只将整个“路径+文件名”作为字节给出,而不是分开的,而且很难分开它们。 如果有人可以帮助我,我将不胜感激。

import subprocess 

p = subprocess.Popen("hdfs dfs -ls <directory>",
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)

for line in p.stdout.readlines():
print(line)

【问题讨论】:

  • 嘿!请向我们展示您编写的一些代码:)
  • @KasiaGogolek 完成
  • 使用python中提供的HDFS CLI库更方便。它具有类似于 os.walk 的功能,您可以在其中获取所有文件名。

标签: python pyspark subprocess hdfs filenames


【解决方案1】:

这给出了列表数据类型的输出

import subprocess
out=subprocess.check_output(["hadoop","fs","-ls","<directory>"] ).split("\n")
out

【讨论】:

    【解决方案2】:

    使用HDFS CLI递归遍历hdfs,

    from hdfs import InsecureClient
    client = InsecureClient(hostname, user)
    
    get_file = []
    for dir_,sub_dir, files in client.walk():
        if files:
            get_file.append(files)
    

    【讨论】:

      【解决方案3】:

      使用这个:

      from subprocess import Popen, PIPE
      hdfs_path = '/path/to/the/designated/folder'
      process = Popen(f'hdfs dfs -ls -h {hdfs_path}', shell=True, stdout=PIPE, stderr=PIPE)
      std_out, std_err = process.communicate()
      list_of_file_names = [fn.split(' ')[-1].split('/')[-1] for fn in std_out.decode().readlines()[1:]][:-1]
      list_of_file_names_with_full_address = [fn.split(' ')[-1] for fn in std_out.decode().readlines()[1:]][:-1]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-10-24
        • 2018-03-06
        • 2021-03-23
        • 2016-09-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多