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
Asked
Active
Viewed 186 times
0
Harsha Biyani
- 6,633
- 9
- 33
- 55
Falcon
- 1
- 1
-
os.rename(src, dst) – Harsha Biyani Dec 29 '21 at 07:12
-
I think this link can solve your question https://stackoverflow.com/questions/10377998/how-can-i-iterate-over-files-in-a-given-directory , see this how can you rename files in python https://stackoverflow.com/questions/2491222/how-to-rename-a-file-using-python – Gautam Jangid Dec 29 '21 at 07:13
2 Answers
0
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.
HIMANSHU PANDEY
- 541
- 8
- 21
-
1Logical!, I modified the code, now it uses regex to determine name as well as extension of files in given directory, and saves newones in the same directory. – HIMANSHU PANDEY Dec 29 '21 at 09:27
0
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.
frippe
- 1,169
- 7
- 14