[英]How to find all textual files regardless of extension that contains only commas and digits?
我必须搜索可能具有任何扩展名的文件。 所有这些文件的特殊属性是它们长度少于五行(小于4 \\ n \\ r),除了换行符之外,所有字符都是数字,空格和逗号。 如何根据内容编写搜索文件的代码?
我很清楚这需要很长时间才能运行。
我的项目不需要Java或Python,我只是提到它们,因为我对它们比较熟悉。 Powershell是值得推荐的。
我正在运行Windows 7系统。
像下面这样的东西应该工作:
valid_chars = set('0123456789, \r\n')
for root, dirs, files in os.walk(base):
for fname in files:
fpath = os.path.join(root, fname)
with open(fpath, 'rb') as f:
lines = []
for i, line in enumerate(f):
if i >= 5 or not all(c in valid_chars for c in line):
break
else:
print 'found file: ' + fpath
您可以使用正则表达式而not all(c in valid_chars for c in line)
:
...
if i >= 5 or not re.match(r'[\d, \r\n]*$', line):
...
如果你使用正则表达式,为了提高效率,请在循环之外使用re.compile
。
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)
你可以使用grep -r
和-l
选项。 -r
允许您在所有文件的目录中递归搜索, -l
仅打印其内容与正则表达式匹配的文件的名称。
grep -r -l '\A([0-9, ]+\s){1,4}[0-9, ]+\Z' directory
这将打印少于5行数字,空格或逗号字符的所有文件的名称列表。
\\ A和\\ Z将检查主题文本的开头和结尾。 [0-9, ]+
查找一系列数字,空格或逗号,后跟\\s
,它是换行符,空格或回车符。 该序列可以重复最多4次,由{1,4}
表示,然后是另一行数据。
在Python中(我只会概述步骤,以便您可以自己编程。但当然可以随意询问您是否可以解决问题):
os.path.walk
查找所有文件(它为您提供所有文件,无论其扩展名如何)。 os.path.isfile
跳过它们。 open
)。 在with
语句中执行以下操作以避免必须手动关闭文件。 regular expression
。 如果不匹配,继续。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.