我正在尝试创建一个代码,根据掩码删除文件夹中的文件。所有包含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 `
还有一些错误。
我是一名初学者,采用业余的方式想要获得PY方面的经验,并且通过并行学习来了解细节。我做错了什么?任何帮助都是有用的。谢谢。文件"D:\Python\Test_folder\Remover v2.py"的第14行,匹配(r'\w\w[_]\w\w\w\w[1][7]\w+[.]\w+', testfolder) # 匹配文件掩码  文件"D:\Python\Test_folder\Remover v2.py"的第9行,在matching函数中 match = re.search(r, s) 文件"c:\Program Files (x86)\Wing IDE Personal 6.0\bin\runtime-python2.7\Lib\re.py"的第146行,使用search方法 return _compile(pattern, flags).search(string)
matching
函数在没有匹配的情况下返回一个字符串似乎是一个特别糟糕的选择。如果您真的认为这需要作为一个单独的函数存在,那么请让它返回一些易于在其他代码中处理的内容,比如None
或False
,并且只在直接与用户交流时使用人性化的表达方式。 - tripleee