I have files with filenames as "lsud-ifgufib-1234568789.png" I want to rename this file as digits only which are followed by last "-" and then save them back in the folder.
Basically I want the final filename to be the digits that are followed by "-".
~ path = 'C:/Users/abc/downloads'
for filename in os.listdir(path):
r = re.compile("(\d )")
newlist = filter(r.match, filename)
print(newlist)
~ How do I proceed further?
CodePudding user response:
You could try a regex
search followed by a path join:
import re
import os
path = 'C:/Users/abc/downloads'
for filename in os.listdir(path):
os.rename(filename, os.path.join(path, re.search("\d (?=\D ?$)", filename).group()))
CodePudding user response:
import re
import pathlib
fileName = "lsud-ifgufib-1234568789.png"
_extn = pathlib.Path(fileName).suffix
_digObj = re.compile(r'\d ')
digFileName = ''.join(_digObj.findall(fileName))
replFileName = digFileName _extn
CodePudding user response:
Assumptions:
- You want to rename files if the file has a hyphen before the number.
- The file may or may not have an extention.
- If the file has an extention, preserve it.
Then would you please try the following:
import re, os
path = 'C:/Users/abc/downloads'
for filename in os.listdir(path):
m = re.search(r'.*-(\d .*)', filename)
if (m):
os.rename(os.path.join(path, filename), os.path.join(path, m.group(1)))