代码之家  ›  专栏  ›  技术社区  ›  Nate

批量重命名目录中的文件

  •  86
  • Nate  · 技术社区  · 16 年前

    是否有一种简单的方法可以使用python重命名目录中已经包含的一组文件?

    例子: 我有一个满是*.doc文件的目录,我想以一致的方式重命名它们。

    x.doc->“新建(x).doc”

    y.doc->“新建(y).doc”

    12 回复  |  直到 6 年前
        1
  •  96
  •   Dzinx    16 年前

    例如,使用 os glob 模块:

    import glob, os
    
    def rename(dir, pattern, titlePattern):
        for pathAndFilename in glob.iglob(os.path.join(dir, pattern)):
            title, ext = os.path.splitext(os.path.basename(pathAndFilename))
            os.rename(pathAndFilename, 
                      os.path.join(dir, titlePattern % title + ext))
    

    然后您可以在示例中使用它,如下所示:

    rename(r'c:\temp\xx', r'*.doc', r'new(%s)')
    

    上面的示例将转换所有 *.doc 文件在 c:\temp\xx 迪尔 new(%s).doc 在哪里 %s 是文件的前一个基名称(不带扩展名)。

        2
  •  112
  •   Cesar Canassa    13 年前

    我更喜欢为我必须做的每个替换编写一个小的一行程序,而不是生成一个更通用和复杂的代码。例如。:

    这将用当前目录中任何非隐藏文件中的连字符替换所有下划线

    import os
    [os.rename(f, f.replace('_', '-')) for f in os.listdir('.') if not f.startswith('.')]
    
        3
  •  21
  •   tzot    16 年前

    如果您不介意使用正则表达式,那么此函数将为您提供重命名文件的强大功能:

    import re, glob, os
    
    def renamer(files, pattern, replacement):
        for pathname in glob.glob(files):
            basename= os.path.basename(pathname)
            new_filename= re.sub(pattern, replacement, basename)
            if new_filename != basename:
                os.rename(
                  pathname,
                  os.path.join(os.path.dirname(pathname), new_filename))
    

    因此,在您的示例中,您可以这样做(假设文件所在的目录为当前目录):

    renamer("*.doc", r"^(.*)\.doc$", r"new(\1).doc")
    

    但也可以回滚到初始文件名:

    renamer("*.doc", r"^new\((.*)\)\.doc", r"\1.doc")
    

    还有更多。

        4
  •  11
  •   kiriloff    11 年前

    我可以简单地重命名文件夹子文件夹中的所有文件

    import os
    
    def replace(fpath, old_str, new_str):
        for path, subdirs, files in os.walk(fpath):
            for name in files:
                if(old_str.lower() in name.lower()):
                    os.rename(os.path.join(path,name), os.path.join(path,
                                                name.lower().replace(old_str,new_str)))
    

    我正在用任何一种情况来代替旧的情况。

        5
  •  6
  •   xsl Fredrik Hedblad    16 年前

    尝试: http://www.mattweber.org/2007/03/04/python-script-renamepy/

    我喜欢我的音乐、电影和 以某种方式命名的图片文件。 当我从 互联网,他们通常不遵循我的 命名约定。我发现了我自己 手动重命名每个文件以适应我的 风格。这真是太快了,所以我 决定写一个程序来做这件事 为了我。

    这个程序可以转换文件名 全部小写,替换中的字符串 文件名随你的需要, 并从中删除任意数量的字符 文件名的前面或后面。

    程序的源代码也可用。

        6
  •  6
  •   harisibrahimkv    12 年前

    我自己写了一个python脚本。它将文件所在目录的路径和要使用的命名模式作为参数。但是,它通过将一个递增的数字(1、2、3等)附加到您提供的命名模式来重命名。

    import os
    import sys
    
    # checking whether path and filename are given.
    if len(sys.argv) != 3:
        print "Usage : python rename.py <path> <new_name.extension>"
        sys.exit()
    
    # splitting name and extension.
    name = sys.argv[2].split('.')
    if len(name) < 2:
        name.append('')
    else:
        name[1] = ".%s" %name[1]
    
    # to name starting from 1 to number_of_files.
    count = 1
    
    # creating a new folder in which the renamed files will be stored.
    s = "%s/pic_folder" % sys.argv[1]
    try:
        os.mkdir(s)
    except OSError:
        # if pic_folder is already present, use it.
        pass
    
    try:
        for x in os.walk(sys.argv[1]):
            for y in x[2]:
                # creating the rename pattern.
                s = "%spic_folder/%s%s%s" %(x[0], name[0], count, name[1])
                # getting the original path of the file to be renamed.
                z = os.path.join(x[0],y)
                # renaming.
                os.rename(z, s)
                # incrementing the count.
                count = count + 1
    except OSError:
        pass
    

    希望这对你有用。

        7
  •  2
  •   frank__aguirre    7 年前
    directoryName = "Photographs"
    filePath = os.path.abspath(directoryName)
    filePathWithSlash = filePath + "\\"
    
    for counter, filename in enumerate(os.listdir(directoryName)):
    
        filenameWithPath = os.path.join(filePathWithSlash, filename)
    
        os.rename(filenameWithPath, filenameWithPath.replace(filename,"DSC_" + \
              str(counter).zfill(4) + ".jpg" ))
    
    # e.g. filename = "photo1.jpg", directory = "c:\users\Photographs"        
    # The string.replace call swaps in the new filename into 
    # the current filename within the filenameWitPath string. Which    
    # is then used by os.rename to rename the file in place, using the  
    # current (unmodified) filenameWithPath.
    
    # os.listdir delivers the filename(s) from the directory
    # however in attempting to "rename" the file using os 
    # a specific location of the file to be renamed is required.
    
    # this code is from Windows 
    
        8
  •  2
  •   Kanmani    7 年前

    我有一个类似的问题,但我想在目录中所有文件的文件名的开头追加文本,并使用了类似的方法。见下例:

    folder = r"R:\mystuff\GIS_Projects\Website\2017\PDF"
    
    import os
    
    
    for root, dirs, filenames in os.walk(folder):
    
    
    for filename in filenames:  
        fullpath = os.path.join(root, filename)  
        filename_split = os.path.splitext(filename) # filename will be filename_split[0] and extension will be filename_split[1])
        print fullpath
        print filename_split[0]
        print filename_split[1]
        os.rename(os.path.join(root, filename), os.path.join(root, "NewText_2017_" + filename_split[0] + filename_split[1]))
    
        9
  •  2
  •   Ajay Chandran    6 年前

    在需要执行重命名的目录中。

    import os
    # get the file name list to nameList
    nameList = os.listdir() 
    #loop through the name and rename
    for fileName in nameList:
        rename=fileName[15:28]
        os.rename(fileName,rename)
    #example:
    #input fileName bulk like :20180707131932_IMG_4304.JPG
    #output renamed bulk like :IMG_4304.JPG
    
        10
  •  1
  •   Jayhello    7 年前

    对于我的目录,我有多个子目录,每个子目录都有很多图像,我想把所有的子目录图像都改成1.jpg~n.jpg。

    def batch_rename():
        base_dir = 'F:/ad_samples/test_samples/'
        sub_dir_list = glob.glob(base_dir + '*')
        # print sub_dir_list # like that ['F:/dir1', 'F:/dir2']
        for dir_item in sub_dir_list:
            files = glob.glob(dir_item + '/*.jpg')
            i = 0
            for f in files:
                os.rename(f, os.path.join(dir_item, str(i) + '.jpg'))
                i += 1
    

    (我自己的答案) https://stackoverflow.com/a/45734381/6329006

        11
  •  1
  •   Dan    6 年前
    #  another regex version
    #  usage example:
    #  replacing an underscore in the filename with today's date
    #  rename_files('..\\output', '(.*)(_)(.*\.CSV)', '\g<1>_20180402_\g<3>')
    def rename_files(path, pattern, replacement):
        for filename in os.listdir(path):
            if re.search(pattern, filename):
                new_filename = re.sub(pattern, replacement, filename)
                new_fullname = os.path.join(path, new_filename)
                old_fullname = os.path.join(path, filename)
                os.rename(old_fullname, new_fullname)
                print('Renamed: ' + old_fullname + ' to ' + new_fullname
    
        12
  •  0
  •   murthy annavajhula    6 年前

    这个代码可以用

    该函数将两个参数f_patth作为重命名文件的路径,并将新名称作为文件的新名称。

    import glob2
    import os
    
    
    def rename(f_path, new_name):
        filelist = glob2.glob(f_path + "*.ma")
        count = 0
        for file in filelist:
            print("File Count : ", count)
            filename = os.path.split(file)
            print(filename)
            new_filename = f_path + new_name + str(count + 1) + ".ma"
            os.rename(f_path+filename[1], new_filename)
            print(new_filename)
            count = count + 1