2015-10-05 229 views
0

幾周前,我正在打印「Hello,World」。現在我正在頭腦中潛入編碼池,我不知道如何游泳。請給我一個救生衣。用Python重命名文件

我有一個目錄多個文件,如:

123456 C01-1-File.pdf

123456 C02-1-File.pdf

123456 C02-2- File.pdf

,並希望取消固定,6位前綴和增加增量的前綴,如:

600 -

601 -

602 -

因此,應將文件重命名爲:

600 - C01-1-File.pdf

601 - C02-1-File.pdf

602 - C02-2-File.pdf

這是我拼湊起來的腳本:

import os 
import glob 
import sys 

def fileRename(): 
    #this section determines file types to work with based on user input 
    path = os.getcwd() 
    a = raw_input('Enter the file extension: ') 
    b = '*' + '.' + str(a) 
    first_lst = sorted(glob.glob(b)) 
    l = len(first_lst) 
    if l > 1: 
     print 'There are ' + str(l) + ' files of the specified type in the current directory' 
    elif l == 1: 
     print 'There is ' + str(l) + ' file of the specified type in the current directory' 
    else: 
     print 'There are no files of the specified type in the current directory' 
     sys.exit() 
    for file in first_lst: 
     print '\t' + file 

    #this section removes a numerical prefix from specified file type 
    x = raw_input('Would you like to remove the prefix from these files? [y/n]: ') 
    if x == 'y': 
     for filename in first_lst: 
      new_filename = filename 
      #while filenames in the list start with a number, remove the number 
      while new_filename[0].isdigit(): 
       new_filename = new_filename[1:] 
      #rename all files that have had the numerical prefix removed 
      if new_filename != filename: 
       print 'Renaming %s to %s' % (filename, new_filename) 
       os.rename(os.path.join(path,filename), os.path.join(path,new_filename)) 

    xx = raw_input('Would you like to add an iterative prefix to these files? [y/n]: ') 

    if xx == 'y': 
        second_lst = sorted(glob.glob(b)) 

        #this creates an iterative list of new prefix numbers 
        x = int(raw_input('Enter the beginning prefix number: ')) 
        working_lst = range(x, x + l) 
        prefix_lst = working_lst[:l] 

      #this combines the prefix list and filename list 
        final_lst = ['{} -{}'.format(x,y) for x, y in zip(prefix_lst,second_lst)] 
        for new in final_lst: 
       print ('Here are the new file names: ') 
       print '\t' + new 

      #THIS IS THE SECTION THAT DOES NOT WORK 
      #this section should rename the files with an iterative prefix 
      third_lst = sorted(glob.glob(b)) 
        user_input = raw_input('Would you like to continue with renaming? [y/n]: ') 
        if user_input == 'y': 
         for file in file_list: 
           print file 
         for i in final_list: 
           print i 
         print 'Renaming %s to %s' % (file, i) 
    else: sys.exit()    


fileRename() 


我玩過的語法和縮進,這將產生以下結果。我遇到的問題是在「你想繼續重命名?」之後的輸出。

這裏有一些照片,顯示輸出:
attempt1,只有右側的輸出是正確的
attempt2,只有左邊的輸出是正確的


什麼我錯過了嗎?有一個更好的方法嗎?

+0

嗯,所以我沒有真正解決您的問題。你的代碼究竟有什麼問題,你想在輸出中有什麼不同? – Salo

+0

啊,現在,對不起,因爲愚蠢。我現在明白了這個問題 – Salo

+0

您必須修復縮進。這是「kaputt」,所以不可能理解屬於哪裏。 – Psytho

回答

0

好吧我試圖修復你的縮進,並發現一些設計上的缺陷。

  1. 刪除前綴時,可能是您將所有文件重命名爲相同的名稱。這意味着當你例如將文件1.jpg,2.jpg3.jpg全部重命名爲.jpg,因此除重命名後的最後一個文件外,所有文件都不再存在!

  2. 它在代碼中變得非常複雜,主要來自於選擇較差的變量名稱(如xxx)以及不使用幫助函數。試着寫的輔助函數只做一兩件事,並明智地爲它們命名:)

因此,這裏是重構的結果和清理,我覺得還是做(至少幾乎)你想要什麼。所以儘量把它當成首發。

import glob 
import sys 


def fileRename(): 
    # this section determines file types to work with based on user input 
    a = raw_input('Enter the file extension: ') 
    b = '*' + '.' + str(a) 
    first_lst = sorted(glob.glob(b)) 
    l = len(first_lst) 
    if l > 1: 
     print('There are ' + str(l) + 
       ' files of the specified type in the current directory') 
    elif l == 1: 
     print('There is ' + str(l) + 
       ' file of the specified type in the current directory') 
    else: 
     print('There are ' 
       'no files of the specified type in the current directory') 
     sys.exit() 
    for file in first_lst: 
     print '\t' + file 

    # this section removes a numerical prefix from specified file type 
    remove_prefix = raw_input('Would you like ' 
           'to remove the prefix from these files? [y/n]: ') 
    new_filenames = [] 
    if remove_prefix == 'y': 
     for filename in first_lst: 
      # while filenames in the list start with a number, remove the number 
      new_filename = remove_leading_number(filename) 
      # rename all files that have had the numerical prefix removed 
      if new_filename != filename: 
       print 'Renaming %s to %s' % (filename, new_filename) 
       new_filenames.append(new_filename) 

    if remove_prefix == 'n': 
     new_filenames = first_lst 

    add_counter = raw_input('Would you like to add an ' 
          'iterative prefix to these files? [y/n]: ') 

    if add_counter == 'y': 
     # this creates an iterative list of new prefix numbers 
     prefix_num_start = int(raw_input('Enter the beginning prefix number: ')) 
     prefix_lst = range(prefix_num_start, prefix_num_start + l) 

     # this combines the prefix list and filename list 
     final_lst = ['{}-{}'.format(x, y) for x, y in zip(prefix_lst, new_filenames)] 
     for new in final_lst: 
      print ('Here are the new file names: ') 
      print '\t' + new 

    # THIS IS THE SECTION THAT DOES NOT WORK 
    # this section should rename the files with an iterative prefix 
    user_input = raw_input('Would you like to continue with renaming? [y/n]: ') 
    if user_input == 'y': 
     for i in final_lst: 
      print i 
      print 'Renaming %s to %s' % (file, i) 
    else: 
     sys.exit() 


def remove_leading_number(filename): 
    while filename[0].isdigit(): 
     filename = filename[1:] 
    return filename 


fileRename() 

快樂編碼!