Batch Renaming of Files in a Directory

前端 未结 13 1492
孤街浪徒
孤街浪徒 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 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
    

提交回复
热议问题