[英]Python - glob.glob with grep?
我对 Python 环境还很陌生,并且正在逐步前进。
我们在一个包含类似信息的文件夹中获得了大约 10,000 个文件,但有一个主要区别。 一些文件包含字符串“string1”,另一组包含“string2”。 只是为了澄清字符串不在文件名中,而是在文件本身中。 文件内容以字符分隔。
我尝试使用 string1 分别创建两个单独的列表 string2 并获得了多行代码但一无所获。 两个列表都应该只包含文件名。
我经常使用grep
来处理这类事情。 在这种情况下,我会使用
编辑添加文件扩展名:
grep -l string1 *.txt > string1_files.txt && grep -l string2 *.txt> string2_files.txt
这个 oneliner 将在当前目录中的txt
文件中搜索string1
,将 output 写入string1_files.txt
并类似地用于string2
从man grep
复制
-l, --files-with-matches
Only the names of files containing selected lines are written to
standard output. grep will only search a file until a match has
been found, making searches potentially less expensive. Path-
names are listed once per file searched. If the standard input
is searched, the string ``(standard input)'' is written.
希望这会有所帮助,但您可能只想 grep 某些文件扩展名
编辑无文件扩展名:(如果它们在问题评论中不可用
grep -l string1 * > string1_files.txt && grep -l string2 *> string2_files.txt
假设您的文件只有您要比较的字符串,您只需要执行
folder = 'foo'
files = glob.glob(os.path.join(folder, "*"))
list1 = []
list2 = []
for file in files:
with open(file, 'r') as f:
if(f.readlines().strip() == 'string1'):
list1.append(file)
else
list2.append(file)
如果您的文件有更多数据,您只需要处理f.readlines()
并正确比较。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.