我正在研究ATBS第9章的“ fillingGaps”项目。该项目如下:编写一个程序,该程序在单个文件夹中查找所有具有给定前缀的文件,例如spam001.txt,并查找编号中的任何空白(例如spam001.txt和spam003.txt,但没有spam002.txt)。让程序重命名所有以后的文件以弥补这一空白。
我试图定义一个正则表达式,该正则表达式忽略文件名的第一部分,并主要通过仅标识以.txt结尾且以.txt开头的文件,重点关注传递给“搜索”的路径中的文本文件。两位数。 (我的文件格式为“ Capitalsquiz1.txt”至“ Capitalsquiz35.txt”,“ Capitals_answers1.txt”至“ Capitals_answers35.txt”,文件夹路径中还有其他文件类型)。
import os, re
# Define regular expression to identify files of given prefix
sequence = re.compile(r'''(.*?) # text preceeding the number prefix
(\d{1|2}) # followed by one or two digits
('.txt')$ # ends with '.txt'
''', re.VERBOSE)
# Define folder path to search
search = input('Please enter folder to search:')
filenames = list(os.walk(search))[0][2] # os.walk returns tuple of three lists(Foldername,subfolders, filenames). List converts it to list of three lists.
# [0][2] picks out the third list (filenames)[2] within the main list (the one that contains all three)[0].
filename = ''.join(filenames)
filename = ''.join(filenames)
text = sequence.search(filename)
skan = text.group(0)
print(text)
# Search for the files that match the regular expression
# Loop through files to identify gaps
正则表达式似乎不起作用,但我不明白为什么。它不断返回“无”
File "C:\Users\peada\Documents\Python\Automate the Boring Stuff\Chapter 9\fillingGaps.py", line 28, in <module>
skan = text.group(0)
AttributeError: 'NoneType' object has no attribute 'group'```
Any help that helps me learn where I went wrong appreciated. I could lookup a solution in minutes but that's pointless.