如何使用 Dir.glob 获取仅文件的列表? [英] How do I get a listing of only files using Dir.glob?

查看:36
本文介绍了如何使用 Dir.glob 获取仅文件的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何只返回指定目录中的文件列表,而不返回目录?

How can I return a list of only the files, not directories, in a specified directory?

我有 my_list = Dir.glob(script_path.join("*"))

这将返回目录中的所有内容,包括子目录.我搜索过,但没有找到答案.

This returns everything in the directory,including subdirectories. I searched but haven't been able to find the answer.

推荐答案

除了 Mark 的回答,Dir.entries 将返回目录.如果您只需要文件,您可以使用 file? 测试每个条目以查看它是文件还是目录.

In addition to Mark's answer, Dir.entries will give back directories. If you just want the files, you can test each entry to see if it's a file or a directory, by using file?.

Dir.entries('/home/theiv').select { |f| File.file?(f) }

/home/theiv 替换为您要在其中查找文件的任何目录.

Replace /home/theiv with whatever directory you want to look for files in.

另外,请查看文件.它提供了大量测试和属性,您可以检索有关文件的信息.

Also, have a look at File. It provides a bunch of tests and properties you can retrieve about files.

这篇关于如何使用 Dir.glob 获取仅文件的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆