【问题标题】:Renaming files with Python使用 Python 重命名文件
【发布时间】:2016-01-01 20:37:44
【问题描述】:

几周前,我正在打印“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中,只有左边的输出是正确的


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

【问题讨论】:

  • 嗯,所以我真的不明白你的问题。您的代码到底有什么问题,您希望输出有什么不同?
  • 啊,对不起,我很愚蠢。我现在明白这个问题了
  • 你必须修复缩进。它是“kaputt”,因此无法理解什么属于哪里。

标签: python list rename file-rename renaming


【解决方案1】:

好的,我尝试修复您的缩进,并在途中发现了一些设计缺陷。

  1. 删除前缀时,您可能会将所有文件重命名为相同的名称。这意味着当你例如将文件1.jpg2.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()

编码愉快!

【讨论】:

    猜你喜欢
    • 2013-08-24
    • 2014-10-10
    • 2010-11-22
    • 2011-01-30
    • 2021-02-20
    • 1970-01-01
    • 2015-04-17
    相关资源
    最近更新 更多