使用Python重命名文件

时间:2015-10-05 08:40:48

标签: python list rename file-rename renaming

几个星期前,我正在打印“Hello,World”。现在我正在潜水,先进入编码池,我不知道如何游泳。请给我一个救生圈。

我在目录中有几个文件,例如:

  

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中,只有左侧的输出是正确的


我错过了什么?有一个更好的方法吗?

1 个答案:

答案 0 :(得分:0)

好的我试着修复你的缩进,发现了一些设计缺陷。

  1. 删除前缀时,可能会将所有文件重命名为同名。这意味着当你例如将文件1.jpg2.jpg3.jpg全部重命名为.jpg,以便重命名后除了最后一个文件之外所有文件都已消失!

  2. 代码中的代码非常复杂,主要来自于选择不良的变量名(如xxx)以及不使用辅助函数。尝试编写完成一件事的辅助函数并明智地命名:)

  3. 所以这是重构和清理的结果,我认为它正在做(至少差不多)你想要的东西。所以尽量把它作为首发。

    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()
    

    快乐的编码!