我是python的初学者。我的任务是:
编写一个程序,在一个文件夹中查找具有给定前缀的所有文件,如spam001.txt、spam002.txt等等,并查找编号中的任何空白(例如,如果有spam001.txt和spam003.txt,但没有spam002.txt)。让程序重命名所有后面的文件来缩小这个差距。在
我已经写了我的代码,它似乎可以工作,但它看起来丑陋,不优雅。尤其是3if语句。我怎样才能缩短它?在
这是我的代码:# My main idea is to copy the file which is not in right order,
# and rename it, then delete it.
import os, re, shutil
# Arguments: folder, prefix
def fillGap(folder,prefix):
# Create regex with prefix + number + extension.
fileRegex = re.compile(r'(%s)((\d)(\d)(\d))\.txt' % prefix)
# Makee sure the path is absolute.
folder = os.path.abspath(folder)
# When I commented the following one line, the program outptu is
# FileNotFoundError: [Errno 2] No such file or directory: 'spam004.txt'
os.chdir(folder) # This line