Richard James
Richard James

Reputation: 3

How can I rename every file that matches a regex?

I want to rename filenames of the form xyz.ogg.mp3 to xyz.mp3.

I have a regex that looks for .ogg in every file then it replaces the .ogg with an empty string but I get the following error:

Traceback (most recent call last):
  File ".\New Text Document.py", line 7, in <module>
    os.rename(files, '')
TypeError: rename() argument 1 must be string, not _sre.SRE_Match

Here is what I tried:

for file in os.listdir("./"):
    if file.endswith(".mp3"):
        files = re.search('.ogg', file)
        os.rename(files, '')

How can I make this loop look for every .ogg in each file then replace it with an empty string?

The file structure looks like this: audiofile.ogg.mp3

Upvotes: 0

Views: 627

Answers (3)

s3cur3
s3cur3

Reputation: 3025

An example using Python 3's pathlib (but not regular expressions, as it's kind of overkill for the stated problem):

from pathlib import Path
for path in Path('.').glob('*.mp3'):
    if '.ogg' in path.stem:
        new_name = path.name.replace('.ogg', '')
        path.rename(path.with_name(new_name))

A few notes:

  • Path('.') gives you a Path object pointing to the current working directory
  • Path.glob() searches recursively, and the * there is a wildcard (so you get anything ending in .mp3)
  • Path.stem gives you the file name minus the extension (so if your path were /foo/bar/baz.bang, the stem would be baz)

Upvotes: 0

Gilles Qu&#233;not
Gilles Qu&#233;not

Reputation: 184985

Would be far more quicker to write a command line :

rename 's/\.ogg//' *.ogg.mp3

(perl's rename)

Upvotes: 0

marcos
marcos

Reputation: 4510

You can do something like this:

for file in os.listdir("./"):
    if file.endswith(".mp3") and '.ogg' in file:
        os.rename(file, file.replace('.ogg',''))

Upvotes: 1

Related Questions