我是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 is to avoid the FileNotFoundError.
# Make a list to contain the file with prefix.
fileNames = list()
for filename in os.listdir(folder):
if re.search(fileRegex, filename):
fileNames.append(filename)
# Make sure the fileName in the list have a right order.
fileNames.sort()
print(fileNames)
# Find the gap through incremting loops
for i in range(len(fileNames)):
mo = re.search(fileRegex, fileNames[i])
if int(mo.group(2)) == i + 1:
continue
# The group(2) has three digits, so it need to 3 Ifs.
# Copy the old file and rename it then delete the old one.
if i + 1 < 10:
shutil.copy
newFileName =prefix + '00' + str(i + 1) + '.txt'
shutil.copy(fileNames[i], newFileName)
os.unlink(fileNames[i])
elif i + 1 < 100:
shutil.copy(fileNames[i], prefix + '0' + str(i+1) + '.txt')
os.unlink(fileNames[i])
else:
shutil.copy(fileNames[i], prefix + str(i+1) + '.txt')
os.unlink(fileNames[i])
folder = '/home/jianjun/spam/'
prefix = 'spam'
fillGap(folder, prefix)
regex可能正在工作,但是如果您正在寻找一个公共前缀,那么您可以使用
str.startswith
函数:然后要找到数字,你可以去掉前缀和文件扩展名(不确定这一步是否必要,为什么需要旧的数字?)公司名称:
^{pr2}$要用前导零填充小数字,您可以使用
{:0>3}.format
,例如,请参见:因此,与其使用
prefix + str(i+1) + '.txt'
和变体,不如将其简化为:假设您在创建数字之前
sort
您的文件现在有一个旧名称和新名称的列表,您可以通过迭代来重命名它们:这是我为这个练习写的脚本。 我希望这对任何人都有帮助
这对我很有效:
相关问题 更多 >
编程相关推荐