Batch Renaming of Files in a Directory

前端 未结 13 1356
孤街浪徒
孤街浪徒 2020-11-27 09:41

Is there an easy way to rename a group of files already contained in a directory, using Python?

Example: I have a directory full of *.doc files an

相关标签:
13条回答
  • 2020-11-27 09:49

    If you would like to modify file names in an editor (such as vim), the click library comes with the command click.edit(), which can be used to receive user input from an editor. Here is an example of how it can be used to refactor files in a directory.

    import click
    from pathlib import Path
    
    # current directory
    direc_to_refactor = Path(".")
    
    # list of old file paths
    old_paths = list(direc_to_refactor.iterdir())
    
    # list of old file names
    old_names = [str(p.name) for p in old_paths]
    
    # modify old file names in an editor,
    # and store them in a list of new file names
    new_names = click.edit("\n".join(old_names)).split("\n")
    
    # refactor the old file names
    for i in range(len(old_paths)):
        old_paths[i].replace(direc_to_refactor / new_names[i])
    

    I wrote a command line application that uses the same technique, but that reduces the volatility of this script, and comes with more options, such as recursive refactoring. Here is the link to the github page. This is useful if you like command line applications, and are interested in making some quick edits to file names. (My application is similar to the "bulkrename" command found in ranger).

    0 讨论(0)
  • 2020-11-27 09:51

    I have this to simply rename all files in subfolders of folder

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

    I am replacing all occurences of old_str with any case by new_str.

    0 讨论(0)
  • 2020-11-27 09:51

    I've written a python script on my own. It takes as arguments the path of the directory in which the files are present and the naming pattern that you want to use. However, it renames by attaching an incremental number (1, 2, 3 and so on) to the naming pattern you give.

    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
    

    Hope this works for you.

    0 讨论(0)
  • 2020-11-27 09:53

    I prefer writing small one liners for each replace I have to do instead of making a more generic and complex code. E.g.:

    This replaces all underscores with hyphens in any non-hidden file in the current directory

    import os
    [os.rename(f, f.replace('_', '-')) for f in os.listdir('.') if not f.startswith('.')]
    
    0 讨论(0)
  • 2020-11-27 09:56

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

    I like to have my music, movie, and picture files named a certain way. When I download files from the internet, they usually don’t follow my naming convention. I found myself manually renaming each file to fit my style. This got old realy fast, so I decided to write a program to do it for me.

    This program can convert the filename to all lowercase, replace strings in the filename with whatever you want, and trim any number of characters from the front or back of the filename.

    The program's source code is also available.

    0 讨论(0)
  • 2020-11-27 10:00
    #  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
    
    0 讨论(0)
提交回复
热议问题