如何使用python脚本从hdfs(hadoop)目录获取文件列表?我试过以下几行:dir=sc.textfile(“hdfs://127.0.0.1:1900/directory“).collect()目录中有文件列表“file1,file2,file3….filen”。通过使用这行,我只得到了所有的内容列表。但我需要一份文件名列表。有人能帮我找出这个问题吗?提前谢谢。
qncylg1j1#
您可以使用os库中的listdir函数 files = os.listdir(path)
files = os.listdir(path)
5t7ly7z52#
对于python 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]
mdfafbf13#
import subprocess path = "/data" args = "hdfs dfs -ls "+path+" | awk '{print $8}'" proc = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) s_output, s_err = proc.communicate() all_dart_dirs = s_output.split() #stores list of files and sub-directories in 'path'
jdgnovmf4#
为什么不让hdfs客户机使用 -C 标记而不是依赖awk或python来打印感兴趣的特定列?即。 Popen(['hdfs', 'dfs', '-ls', '-C', dirname]) 之后,在新行上拆分输出,然后您将得到路径列表。下面是一个示例以及日志记录和错误处理(包括当目录/文件不存在时):
-C
Popen(['hdfs', 'dfs', '-ls', '-C', dirname])
from subprocess import Popen, PIPE import logging logger = logging.getLogger(__name__) FAILED_TO_LIST_DIRECTORY_MSG = 'No such file or directory' class HdfsException(Exception): pass def hdfs_ls(dirname): """Returns list of HDFS directory entries.""" logger.info('Listing HDFS directory ' + dirname) proc = Popen(['hdfs', 'dfs', '-ls', '-C', dirname], stdout=PIPE, stderr=PIPE) (out, err) = proc.communicate() if out: logger.debug('stdout:\n' + out) if proc.returncode != 0: errmsg = 'Failed to list HDFS directory "' + dirname + '", return code ' + str(proc.returncode) logger.error(errmsg) logger.error(err) if not FAILED_TO_LIST_DIRECTORY_MSG in err: raise HdfsException(errmsg) return [] elif err: logger.debug('stderr:\n' + err) return out.splitlines()
kuhbmx9i5#
使用子流程
import subprocess p = subprocess.Popen("hdfs dfs -ls <HDFS Location> | awk '{print $8}'", shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) for line in p.stdout.readlines(): print line
编辑:不带python的答案。第一个选项也可以用于递归打印所有子目录。最后一个重定向语句可以根据您的要求省略或更改。
hdfs dfs -ls -R <HDFS LOCATION> | awk '{print $8}' > output.txt hdfs dfs -ls <HDFS LOCATION> | awk '{print $8}' > output.txt
编辑:更正awk命令中缺少的引号。
5条答案
按热度按时间qncylg1j1#
您可以使用os库中的listdir函数
files = os.listdir(path)
5t7ly7z52#
对于python 3:
mdfafbf13#
jdgnovmf4#
为什么不让hdfs客户机使用
-C
标记而不是依赖awk或python来打印感兴趣的特定列?即。
Popen(['hdfs', 'dfs', '-ls', '-C', dirname])
之后,在新行上拆分输出,然后您将得到路径列表。下面是一个示例以及日志记录和错误处理(包括当目录/文件不存在时):
kuhbmx9i5#
使用子流程
编辑:不带python的答案。第一个选项也可以用于递归打印所有子目录。最后一个重定向语句可以根据您的要求省略或更改。
编辑:更正awk命令中缺少的引号。