2016-12-08 29 views
0

我是一名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) 
+3

如果代碼工作,但你想提高它,嘗試http://codereview.stackexchange.com/ – Stidgeon

+2

我投票關閉這個問題進行摘主題,因爲它屬於codereview.stackexchange.com – demongolem

+0

@demongolem關於堆棧溢出的問題關於堆棧溢出上或下的話題,而不是是否有另一個堆棧交換站點_may_可以採取的問題。 – Peilonrayz

回答

0

正則表達式可能是工作,但如果你正在尋找一個共同的前綴,那麼你可能會堅持使用str.startswith功能:

files = [filename for filename in os.listdir(folder) if filename.startswith('spam')] 

然後找到數字你可以只刪除前綴和文件擴展名(不知道這一步是否有必要,爲什麼你需要舊數字?):

numbers = [int(filename.lstrip('spam').rstrip('.txt')) for filename in files] 

爲了填補小的數字有前導零,你可能只需要使用{:0>3}.format,例如參見:

>>> '{:0>3}'.format(2) 
002 

因此而不是使用prefix + str(i+1) + '.txt'和變型可簡化爲:

newfilenames = ['spam{:0>3}.txt'.format(number+1) for number in range(len(files))] 

假設你sort文件在創建數字之前,您現在有一箇舊名稱和新名稱列表,您可以對其重新命名:

for oldname, newname in zip(files, newfilenames): 
    shutil.copy(oldname, newname) 
    os.unlink(oldname) 
+0

非常感謝。它看起來更優雅。 – ShiJianjun

+0

@石建軍沒問題,如果有幫助,我很高興。 – MSeifert

+0

@史建軍如果真的幫了你的忙,可以隨時接受或者回復。 – MSeifert

0

這爲我工作:

def gaps(dire, prefix): 

    import os, re, shutil 

    folder = os.path.abspath(dire) 
    sablon = re.compile(r'''(%s)(\d\d\d).txt''' % prefix) 
    matchlist = [] 

    for filename in os.listdir(folder): 
     match = sablon.match(filename) 
     if match: 
      matchlist.append(filename) 
      if int(match.group(2)) == len(matchlist): 
       continue 
      else: 
       print(filename + ' is the ' + str(len(matchlist)) + 'th file') 
       if len(matchlist) < 9: 
        print(filename + ' will be renamed: ' + prefix + '00' + str(len(matchlist)) + '.txt') 
        newname = prefix + '00' + str(len(matchlist)) + '.txt' 
        oldname = os.path.join(folder, filename) 
        newname = os.path.join(folder, newname) 
        shutil.move(oldname, newname) 

       elif 10 <= len(matchlist) < 100: 
        print(filename + ' will be renamed: ' + prefix + '0' + str(len(matchlist)) + '.txt') 
        newname = prefix + '0' + str(len(matchlist)) + '.txt' 
        oldname = os.path.join(folder, filename) 
        newname = os.path.join(folder, newname) 
        shutil.move(oldname, newname) 
相關問題