2012-10-25 21 views
0

我試圖用python更改列表中的項目的編號,但似乎無論我做什麼,它都被放入數字順序。在python/tkinter中用正則表達式更改文件的名稱

說我在列表中有下列項目稱爲項目

items = ['1. item1', '2. item2', '3. item3', '4. item4'] 

它很容易想象這樣的,所以這裏是目前的訂單

1. item1 
2. item2 
3. item3 
4. item4 

從另一個功能重新排列順序是:

3. item3 
1. item1 
4. item4 
2. item2 

現在,功能,我遇到了簡單的問題ES文件與他們的位置相對應,所以它現在將是:

1. item3 
2. item1 
3. item4 
4. item2 

的問題是,這些數字被放回數字順序。我的列表項是在一個特定的順序,我需要的產品要根據自己的列表中的位置

def order(self, directory): 
    i = 1 
    #print self.files 
    for filename in os.listdir(directory): 
     if filename in self.files: #if the current file in the directory is part of the files list 
      newfile = re.sub(r'^[0-9][.]',"",filename) #remove the number and decimal from the beginning 
      os.rename(directory + "/" + filename, directory + "/" + str(i) + ". " + newfile) #rename it with a new number and decimal 
      i = i + 1 
      #print newfile 

回答

1

嘗試,而不是i使用編號 - 項目的索引列表中的

os.rename(directory + "/" + filename, directory + "/" + str(self.files.index(filename)) + ". " + newfile) 

因爲我不確定os.listdir如何生成文件的順序。

+0

它可以工作,但它從0開始,而不是從1開始。因此,如果item3是第一個位置,它將被標記爲0. item 3而不是1. item3 – user1104854

+1

'self.files.index(filename)+ 1' then。 .. – mgilson

+0

好吧,我認爲這只是連接它。仍然習慣於python。謝謝 – user1104854