java - 如何查找所有文本文件而不考虑仅包含逗号和数字的扩展名?

标签 java python search powershell grep

我必须搜索可能具有任何扩展名的文件。所有这些文件的特殊属性是它们的长度小于五行(小于 4\n\r),除换行符外,所有字符都是数字、空格和逗号。我将如何编写根据文件内容搜索文件的代码?

我很清楚这需要很长时间才能运行。

我的项目不需要 Java 或 Python,我只是简单地提到了它们,因为我对它们比较熟悉。 Powershell 是一个有值(value)的建议。

我运行的是 Windows 7 系统。

最佳答案

import os

expected_chars = set(' ,1234567890\n\r')
nlines = 5
max_file_size = 1000  # ignore file longer than 1000bytes, this will speed things up


def process_dir(out, dirname, fnames):
    for fname in fnames:
    fpath = os.path.join(dirname, fname)

    if os.path.isfile(fpath):

        statinfo = os.stat(fpath)

        if statinfo.st_size < max_file_size: 
            with open(fpath) as f:
                # read the first n lines
                firstn = [ f.readline() for _ in range(nlines)]

                # if there are any more lines left this is not our file
                if f.readline():
                    continue

                # if the first n lines contain only spaces, commas, digits and new lines
                # this is our kind of file add it to the results.
                if not set(''.join(firstn)) - expected_chars:
                    out.append(fpath)


out = []
path.walk("/some/path/", process_dir, out)

关于java - 如何查找所有文本文件而不考虑仅包含逗号和数字的扩展名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13039958/

相关文章:

java - 如何模拟返回模拟对象的方法

python - 我认为 jupyter-qtconsole 已损坏,因为我运行的是 os x 10.10.5。不更新怎么解决?

算法 - 树中所有节点的最大距离

iphone - 在iPhone SDK中查找带有通配符的文件名

magento - 为什么 Magento 搜索同时显示可配置产品和简单产品?

java - HashMap 删除不起作用

java - TFS Java SDK 在 Tomcat 上运行缓慢

java - 从应用注册中列出 Azure 存储帐户容器时,受众验证失败

python - 遍历字典以替换前导零?

python - 撤消 Pandas 数据框