我必须搜索可能具有任何扩展名的文件。所有这些文件的特殊属性是它们的长度小于五行(小于 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/