簡體   English   中英

使用 Python 從 HDFS 中提取文件名

[英]Extract the names of files from HDFS using Python

我正在使用 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)

這給出了列表數據類型的輸出

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

使用遞歸遍歷 hdfs 的HDFS CLI

from hdfs import InsecureClient
client = InsecureClient(hostname, user)

get_file = []
for dir_,sub_dir, files in client.walk():
    if files:
        get_file.append(files)

使用這個:

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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM