【问题标题】:How to check all the folder inside files and subfolder inside files have particular string present如何检查文件中的所有文件夹和文件中的子文件夹是否存在特定字符串
【发布时间】:2021-09-07 21:41:58
【问题描述】:
  • 我有文件夹和文件
  • 我还有子文件夹和文件
  • 我需要搜索同一文件中也存在的特定字符串,而其他字符串不存在
  • 所有文件都在.txt
  • 我需要检查文件中哪些字符串 20210624 存在于文件中,而字符串 20210625 不在文件中
  • 我的输出返回文件名
import os
match_str = ['20210624']
not_match_str =  ['20210625']
for root, dirs, files in os.walk(path):
    for name in files:
        if name.endswith((".txt")):
             ## search files with match_str `20210624`  and not_match_str `20210625`

我可以使用import walk

【问题讨论】:

  • 获取文件后必须阅读每个文件。然后您可以检查文件中是否存在数字
  • @PCM 请不要进行这种无意义的编辑。添加诸如operating-systemalgorithmlist 之类的通用标签并不能帮助任何人更好地理解这些问题;你提出的大部分修改都是关于可怕的问题,这些问题本可以变得不那么糟糕;但您只是决定建议添加一个没有实际附加价值的标签。
  • 在我的回答中添加了它。

标签: python operating-system


【解决方案1】:

您可以将glob.glob()方法中的recursive关键字参数设置为True,以便程序递归搜索文件夹、子文件夹等文件。

from glob import glob

path = 'C:\\Users\\User\\Desktop'
for file in glob(path + '\\**\\*.txt', recursive=True):
    with open(file) as f:
        text = f.read()
        if '20210624'  in text and '20210625' not in text:
            print(file)

如果您不想打印文件的完整路径;只有文件名,然后:

from glob import glob

path = 'C:\\Users\\User\\Desktop'
for file in glob(path + '\\**\\*.txt', recursive=True):
    with open(file) as f:
        text = f.read()
        if '20210624'  in text and '20210625' not in text:
            print(file.split('\\')[-1])

为了使用os.walk() 方法,您可以使用str.endswith() 方法(就像您在帖子中所做的那样),如下所示:

import os

for path, _, files in os.walk('C:\\Users\\User\\Desktop'):
    for file in files:
        if file.endswith('.txt'):
            with open(os.path.join(path, file)) as f:
                text = f.read()
                if '20210624'  in text and '20210625' not in text:
                    print(file)

并在最大级别的子目录中搜索:

import os

levels = 2
root = 'C:\\Users\\User\\Desktop'
total = root.count('\\') + levels

for path, _, files in os.walk(root):
    if path.count('\\') > total:
        break
    for file in files:
        if file.endswith('.txt'):
            print(os.path.join(path, file))

【讨论】:

  • 有没有我只能搜索2级子文件夹
  • @sim 是的,我添加了。
【解决方案2】:

您可以通过pathlibglob 实现此目的。

import pathlib
path = pathlib.Path(path)
maybe_valids = list(path.glob("*20210624*.txt"))
valids = [elem for elem in maybe_valids if "20210625" not in elem.name]
print(valids)

maybe_valids 列表是使用包含“20210624”并以 .txt 结尾的每个元素创建的,而 valids 是不包含“20210625”的元素。

【讨论】:

  • 我认为 OP 想在文件中找到字符串,而不是文件名。
  • 引用 OP,“我的输出返回文件名”,所以我认为这是期望的行为
  • 但是 OP 的前一点,“我需要检查...存在于文件中...”,使问题变得相当模棱两可。
【解决方案3】:

从这里继续-

if name.endswith((".txt")):
   f = file.read(name,mode='r')
   a = f.read()
   if match_str[0] in f.read():
      # Number is present

如果你有多个 match_str,你也可以使用 for 循环来阅读。 同样,您可以使用not in关键字来检查not_match_str

【讨论】:

    【解决方案4】:

    您可以通过几个简单的 shell 命令获取文件名:

    find . -name "*.txt" | xargs grep -l "20210624" | xargs grep -L "20210625"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-27
      • 1970-01-01
      • 2018-11-17
      • 2016-05-04
      • 1970-01-01
      相关资源
      最近更新 更多