我是一名Python初學者。我有這個任務:編寫一個python程序,查找具有給定前綴的所有文件並填補空白
編寫一個程序,在一個文件夾中找到具有給定前綴的所有文件,如spam001.txt,spam002.txt等,並找出編號中的任何空白(如if有spam001.txt和spam003.txt,但沒有spam002.txt)。讓程序重命名所有後來的文件來縮小這個差距。
我寫了我的代碼,它似乎工作,但它看起來很醜,不優雅。尤其是3條if語句。我怎樣才能縮短它?
這裏是我的代碼:
# 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)
如果代碼工作,但你想提高它,嘗試http://codereview.stackexchange.com/ – Stidgeon
我投票關閉這個問題進行摘主題,因爲它屬於codereview.stackexchange.com – demongolem
@demongolem關於堆棧溢出的問題關於堆棧溢出上或下的話題,而不是是否有另一個堆棧交換站點_may_可以採取的問題。 – Peilonrayz