[英]Get list of files from hdfs (hadoop) directory using python script
[英]Is there any way to list out files from Hadoop hdfs and store only the file names to the local and not the actual file itself?
有什么方法可以列出 Hadoop hdfs 中的文件并仅将文件名存储到本地?
例子:
我有一个文件india_20210517_20210523.csv 。 我目前正在使用 copytolocal 命令将文件从 hdfs 复制到本地,但将文件复制到本地非常耗时,因为文件很大。 我只需要存储在 a.txt 文件中的文件的名称,以使用 bash 脚本执行剪切操作。
请帮助我
最简单的方法是使用以下命令。
hdfs dfs -ls /path/fileNames | awk '{print $8}' | xargs -n 1 basename > Output.txt
这个怎么运作:
hdfs dfs -ls : This will list all the information about the path
awk '{print $8}' : To print the 8th column of the output
xargs -n 1 basename : To get the file names alone excluding the path
> Output.txt : To store the file names to a text file
希望这能回答你的问题。
如果您想以编程方式执行此操作,您可以使用 Hadoop 中的FileSystem和FileStatus对象:
此类应用程序的代码如下所示:
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.*;
import java.io.File;
import java.io.PrintWriter;
public class Dir_ls
{
public static void main(String[] args) throws Exception
{
// get input directory as a command-line argument
Path inputDir = new Path(args[0]);
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(conf);
if(fs.exists(inputDir))
{
// list directory's contents
FileStatus[] fileList = fs.listStatus(inputDir);
// create file and its writer
PrintWriter pw = new PrintWriter(new File("output.txt"));
// scan each record of the contents of the input directory
for(FileStatus file : fileList)
{
if(!file.isDirectory()) // only take into account files
{
System.out.println(file.getPath().getName());
pw.write(file.getPath().getName() + "\n");
}
}
pw.close();
}
else
System.out.println("Directory named \"" + args[0] + "\" doesn't exist.");
}
}
因此,如果我们想列出 HDFS 的根 ( .
) 目录中的文件,我们将这些文件作为其下的内容(注意我们都有目录和文本文件):
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.