Home > Software design >  How to rename part of a filename represented as string in Python script
How to rename part of a filename represented as string in Python script

Time:12-30

If I have file names Falcon_01.cpp , Falcon_02.cpp, Falcon_03.cpp ,....and many more then how should change all the file names in that specific directory to code_01.cpp,code_02.cpp,.. basically how I can replace just a suffix of all file names in single code

CodePudding user response:

pathlib makes this quite convenient:

from pathlib import Path
import re

parent_dir = Path("<path_to_dir>")
pattern = re.compile(r"^Falcon_[0-9] \.cpp$")
falcon_files = (
    file
    for file in parent_dir.glob("Falcon_*.cpp")
    if file.is_file() and pattern.match(file.name)
)

for file in falcon_files:
    file.rename(file.with_name(file.name.replace("Falcon", "code")))

The regex may not be strictly necessary in your case, but I threw it in there to guarantee that only exact matches are renamed, should there be some Falcon_no_match_1234.cpp file in there somewhere.

CodePudding user response:

You can get the directory of files in FILES_DIR, and run the below script

import os, re
FILES_DIR = r'...\...\...\...'
os.chdir(FILES_DIR)
files = os.listdir(os.getcwd())

for file in files:
    if re.match('Falcon. \.cpp', file):
        os.rename(file, 'code'   file[file.find('Falcon') 6:])

This will rename all files starting with Falcon and ending with .cpp.

  • Related