Python-glob.glob和grep?

Python-glob.glob和grep?,python,grep,glob,os.path,Python,Grep,Glob,Os.path,我对Python环境相当陌生,并逐渐朝着自己的方向前进 我们在一个包含类似信息的文件夹中得到了大约10000个文件,但有一个主要区别。某些文件包含字符串“string1”,而另一组包含字符串“string2”。只是为了澄清字符串不在文件名中,而是在文件本身中。文件内容以字符分隔 我试图用string1和string2分别创建两个单独的列表,得到了不同的代码行,但都没有结果。两个列表都应该只包含文件名。假设您的文件只包含要比较的字符串,您只需要 folder = 'foo' files = glo

我对Python环境相当陌生,并逐渐朝着自己的方向前进

我们在一个包含类似信息的文件夹中得到了大约10000个文件,但有一个主要区别。某些文件包含字符串“string1”,而另一组包含字符串“string2”。只是为了澄清字符串不在文件名中,而是在文件本身中。文件内容以字符分隔


我试图用string1和string2分别创建两个单独的列表,得到了不同的代码行,但都没有结果。两个列表都应该只包含文件名。

假设您的文件只包含要比较的字符串,您只需要

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并进行适当的比较。

我经常使用grep来处理这类事情。在这种情况下,我会使用

编辑以添加文件扩展名:

此oneliner将在当前目录中的txt文件中搜索string1,并将输出写入string1_files.txt,类似地,将输出写入string2

从曼格雷普那里抄袭

希望这有点帮助,但您可能只希望grep某些文件扩展名

无文件扩展名编辑:如果问题注释中的文件扩展名不可用

grep -l string1 * > string1_files.txt && grep -l string2 *> string2_files.txt 

你说得对。但很难说他的档案里有什么。这是一个通用的解决方案,我可能有点神秘。这些文件包含数千行生产订单详细信息。我要查找的字符串位于文件头中。但是没有明确提到标题。因此只需将f.readlines.strip更改为f.readlines[0]。strip准确地说,输出应该是两个列表。一个是包含string1的文件名的列表,另一个是包含string2的文件名的列表。抱歉,太神秘了。请告诉我们您正在搜索哪些文件扩展名。我的答案只看TXT,但适应其他扩展非常简单——文件没有扩展名。它们采用EDIFACT标准。然后在我的答案中尝试类似于“”而不是“.txt”的内容
 -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 -l string1 * > string1_files.txt && grep -l string2 *> string2_files.txt