How To Batch Modify Multiple Files Name In Python

In python, you need to use the python os module to handle files and folders. Before using the python os module, you need to import the os module with the command import os. Then you can call the related function of the os module in the format of os.function_name().

1. Common Python os Module Functions.

  1. os.rename(old_file_name, new_file_name) : Rename a file name.
  2. os.remove(file_name) : Remove the file.
  3. os.mkdir(folder_name) : Create a new directory.
  4. os.rmdir(folder_name) :Remove a directory.
  5. os.getcwd() : Get current working directory.
    >>> import os
    >>> 
    >>> os.getcwd()
    '/Users/hello/Desktop'
  6. os.chdir(dir_name) : Change the current directory.
    >>> os.chdir('/usr/local')
    >>>
    >>> os.getcwd()
    '/usr/local'
    
  7. os.listdir(dir_name) : List out the directory content.
    >>> os.listdir('.')
    ['bin', '.com.apple.installer.keep', 'include', 'sbin', 'etc', 'Homebrew', 'var', 'mysql-8.0.23-macos10.15-x86_64', 'Caskroom', 'mysql', 'lib', 'opt', 'Frameworks', 'Cellar', 'share']

2. Batch Modify Multiple Files Name Example.

import os
# The rename flag.
# if set flag value to 1 means adds special character to the file name.
# if set flag value to 2 means removes special character from the file name.
flag = 1

dir_name = '/usr/loca/var'

special_character = 'Test_'

# Gets all the files in the specified folder
file_list = os.listdir(dir_name)

# Iterate the above file list object.
for file in file_list:   
    if flag==1:
        # When the flag value equals 1.
        # Add prefix to the file name.
        new_name = special_character + file
    elif flag==2:
        # When the flag value is 2
        # Get the special_character length.
        len = len(special_character)
        # Get part of the old file name as the new file name.
        new_name = s[num:]
    
    # Rename the file from old name to new name.
    os.rename(dirname + file,dirname+new_name)

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.