【问题标题】:Delete certain files from a directory using regex regarding their file names使用关于文件名的正则表达式从目录中删除某些文件
【发布时间】:2018-01-21 08:38:10
【问题描述】:

在这里,我正在尝试创建一个代码,该代码将根据掩码删除文件夹中的文件。应删除所有包含 17 的文件 文件名格式为 ??_????17*.*,在哪里? - 任何符号 1..n、A..z、_ 和 17 - 在任何文件中(其他文件也包含 18),其扩展名无关紧要。文件 AB_DEFG17Something.Anything - Copy (2).txt

的某些示例
import os
import re

dir_name = "/Python/Test_folder"         # open the folder and read files
testfolder = os.listdir(dir_name)

def matching(r, s):                      # condition if there's nothing to match
match = re.search(r, s)
if match:
return match.group()
return "Files don't exist!"

matching(r'^\w\w\[_]\w\w\w\w\[1]\[7]\w+\[.]\w+', testfolder)  # matching the file's mask

for item in testfolder.index(matching):
if item.name(matching, s):
os.remove(os.path.join(dir_name, item))

# format of filenames not converted :  ??_????17*.* 
# convert for python separarately   :  [\w][\w][_\w][\w][\w][\w]\[1]\[7][\w]+[\.][\w]+
# ? - Any symbol 1..n,A..z \w repeating is * 
# * - Any number of symbols 1..n, A..z
# _ and 17 - in any files `

也有一些错误。

文件“D:\Python\Test_folder\Remover v2.py”,第 14 行,在 matching(r'\w\w[_]\w\w\w\w[1][7]\w+[.]\w+', testfolder) # 匹配文件的掩码  文件“D:\Python\Test_folder\Remover v2.py”,第 9 行,匹配中 匹配 = re.search(r, s) 搜索中的文件“c:\Program Files (x86)\Wing IDE Personal 6.0\bin\runtime-python2.7\Lib\re.py”,第 146 行 return _compile(pattern, flags).search(string)

我是一个初学者,想以业余方式获得 PY 方面的经验,并行学习细节。我究竟做错了什么?任何帮助都会很有用。谢谢

【问题讨论】:

  • shell 已经支持通过通配符删除文件。无论如何,您的正则表达式似乎与问题陈述中的 glob 通配符并不特别密切相关。 Python 的glob 模块在这里可能是更好的选择。
  • 对于 Python 问题,您必须确保缩进正确。让我们猜测哪些错误是代码中的实际错误,而不是由草率的复制/粘贴引起的问题,这是在浪费每个人的时间。尝试将代码粘贴为单个块,然后用鼠标选择该块,然后键入 ctrl-k 以缩进为代码。 (这似乎不适用于本网站的移动版本。)另请参阅help
  • 17_ 只是匹配自己,没有理由将它们放在字符类中。 [ 之前的反斜杠在您的尝试中将其变成 not 字符类。
  • matching 在不匹配的情况下返回一个字符串似乎是一个特别糟糕的选择。如果你真的认为这需要是一个单独的函数,让它返回一些在你的其他代码中易于处理的东西,比如NoneFalse,并且只在直接与 uer 通信时使用人性化的表示。

标签: python regex


【解决方案1】:

不要重新发明轮子,而是使用glob()

import os
from glob import glob

for file in glob('/Python/Test_folder/AB_CDEF17*.*'):
    os.remove(file)

【讨论】:

    【解决方案2】:

    使用glob.glob

    for filename in glob.glob(os.path.join(dirname, "AB_CDEF17*.*")):
        try:
            # Trying to remove a current file
            os.remove(os.path.join(dirname, filename))
        except EnvironmentError:
            # You don't have permission to do it
            pass
    

    使用os.scandirre.match

    pattern = re.compile(r"AB_CDEF17\w+\.\w+")
    for filename in os.scandir(dirname):
        if pattern.match(filename):
            try:
                os.remove(os.path.join(dirname, filename))
            except EnvironmentError:
                pass
    

    【讨论】:

      【解决方案3】:

      你可以试试glob解决方案

      例如,这些是文件夹中的文件

      ~/Test-folder$ ls *.txt -1
      AB_DEFG17Sitanything.n.txt
      AB_DEFG17SOManything.copy(2).txt
      AB_DEFG17SOManything.nis.txt
      AB_DEFG17SOManything.n.txt
      AB_DEFG18SOManything.n.txt
      AB_DEFG28SOManything.n.txt
      AB_PIZG17SOManything.piz.txt
      AB_PIZG28SOManything.n.txt
      AB_PIZG76SOManything.n.txt
      

      我的代码

      import glob
      r = [f for f in glob.glob("*.txt") if "AB_DEFG" in f or "17" in f]
      for f in r:
          print (f)
      

      你会得到

      AB_DEFG17SOManything.n.txt
      AB_DEFG17SOManything.nis.txt
      AB_PIZG17SOManything.piz.txt
      AB_DEFG17Sitanything.n.txt
      AB_DEFG28SOManything.n.txt
      AB_DEFG17SOManything.copy(2).txt
      AB_DEFG18SOManything.n.txt
      

      我忘记添加删除解决方案

      import glob,os
      r = [f for f in glob.glob("*.txt") if "AB_DEFG" in f or "17" in f]
      for f in r:
          os.remove(f)
      

      只有两个文件会保留

      AB_PIZG28SOManything.n.txt
      AB_PIZG76SOManything.n.txt
      

      【讨论】:

        【解决方案4】:

        您可以直接在 shell 中使用以下命令:

        cd $PATH; for inode in $(ls -il AB_CDEF17*.* | awk '{print $1}'); do find . -type f -inum $inode -exec rm -i {} \;; done
        
        • cd $PATH; 转到有问题的文件夹
        • $(ls -il AB_CDEF17*.* | awk '{print $1}') 将打印您当前目录中所有文件的编号,我正在使用这个绕道因为看起来文件名中有空格,因此rm 命令将无法在它们上正常工作.
        • find . -type f -inum $inode -exec rm -i {} \;; 根据文件编号查找文件,并在征得您的许可后将其删除。

        如果你确定你在做什么并且你真的想将它嵌入到一些 python 代码中:

        from subprocess import call
        call('cd $PATH; for inode in $(ls -il AB_CDEF17*.* | awk '{print $1}'); do find . -type f -inum $inode -exec rm -f {} \;; done') 
        

        注意:输入rm -f,文件将被删除,无需您确认

        【讨论】:

          猜你喜欢
          • 2018-06-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-10-23
          • 1970-01-01
          相关资源
          最近更新 更多