【问题标题】:Combining subproccess.os with regex to get a filtered list of directories/files将 subproccess.os 与正则表达式结合以获得过滤后的目录/文件列表
【发布时间】:2019-11-15 07:41:59
【问题描述】:

我是编码新手,在使用带有正则表达式的 subprocess.os 时遇到了困难。我正在尝试获取以大写 C 开头的所有文件和目录的列表。这就是我到目前为止所得到的...

home = subprocess.os.path.expanduser("~")

FilesDirsStartingWithC = []

for (dir, subdir, files) in subprocess.os.walk(home):
    match = re.findall(r'^C\w+')
    for i in match:
        FilesDirsStartingWithC.append(i)
print(FilesDirsStartingWithC)

我意识到第一个 for 语句和 append 语句之间的部分是错误的,但我不知道如何修复它。任何帮助将非常感激!谢谢你:)

【问题讨论】:

  • 您似乎在re.findall中遗漏了一个参数
  • 如果您的问题得到解答,请接受。

标签: python regex for-loop subprocess file-search


【解决方案1】:

你不需要使用 re 模块。它只是 os.walk() 和 .startswith():

import os

catalogs = []
for root, dirs, files in os.walk('D:/'):
    for Dir in dirs:
        if Dir.startswith('C'):
            catalogs.append(Dir)

print(catalogs)

祝你好运!

【讨论】:

    【解决方案2】:

    用匹配的列表扩展你的:

    home = subprocess.os.path.expanduser("~")
    
    FilesDirsStartingWithC = []
    
    for (dirs, subdirs, files) in subprocess.os.walk(home):
        FilesDirsStartingWithC.extend(re.findall('^C\w+', ''.join(dirs)))
        FilesDirsStartingWithC.extend(re.findall('^C\w+', ''.join(subdirs)))
        FilesDirsStartingWithC.extend(re.findall('^C\w+', ''.join(files)))
    print(FilesDirsStartingWithC)
    

    【讨论】:

      【解决方案3】:

      如果您需要遍历并捕获 directoriesfiles,您可以按照 @min-protector 之前的建议进行操作,但合并目录、d 和 files, f、第一:

      import os
      
      paths = []
      for r, d, f in os.walk('/home/'):
      
          d_and_f = d + f
      
          for item in d_and_f:
              if item.startswith('C'):
                  paths.append(os.path.join(os.sep, r, item))
      

      请注意,我使用 os.path.join 将根 r 添加到目录和文件路径中,以确保识别重复。没有这个,\path1\C1\path2\C1 的输出将是 ['C1', 'C1']

      或者你可以使用list List Comprehensions:

      paths = [os.path.join(os.sep, r,item) 
                  for r,d,f in os.walk('/home/') 
                  for item in d + f 
                  if item.startswith('C')]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-02-25
        • 1970-01-01
        • 1970-01-01
        • 2019-09-21
        • 1970-01-01
        • 2011-08-14
        • 1970-01-01
        相关资源
        最近更新 更多