【问题标题】:Python - glob.glob with grep?Python - glob.glob 与 grep?
【发布时间】:2020-04-27 19:05:19
【问题描述】:

我对 Python 环境还很陌生,正在逐步前进。

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

我尝试使用 string1 分别创建两个单独的列表 string2 并获得了多行代码但无济于事。两个列表都应该只包含文件名。

【问题讨论】:

  • 准确地说,输出应该是两个列表。一个文件名包含 string1,另一个文件名包含 string2。对不起,我很神秘
  • 请告诉我们您在搜索哪些文件扩展名。我的回答只查看 txts 但适应其他扩展名相当简单
  • 文件没有扩展名。它们符合 EDIFACT 标准。
  • 然后在我的回答中尝试类似“”而不是“.txt”

标签: python grep glob os.path


【解决方案1】:

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

编辑添加文件扩展名:

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

这个 oneliner 将在当前目录中的 txt 文件中搜索 string1,并将输出写入 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 某些文件扩展名

编辑无文件扩展名:(以防它们在问题 cmets 中不可用

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

【讨论】:

    【解决方案2】:

    假设你的文件只有你想比较的字符串,你只需要这样做

    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()并正确比较即可。

    【讨论】:

    • 你是对的。但很难说他的档案里有什么。这是一个通用的解决方案
    • 抱歉,我可能有点神秘。这些文件包含数千行生产订单详细信息。我要查找的字符串位于文件的标题中。但是没有明确提到标题。
    • 所以只需将 f.readlines().strip() 更改为 f.readlines()[0].strip()
    猜你喜欢
    • 2016-10-03
    • 2013-11-08
    • 2020-05-19
    • 1970-01-01
    • 2019-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多