Alex
Alex

Reputation: 31

Python, I want to replace parts of filenames for a group of files

I want to write a program that asks you what you want to replace and what to replace it with.

I have a big group of files with different extensions and I want to replace parts of the file names but all of the parts that I want to replace are the same. I want to do it to every file in the folder

So I have files like

ABC.txt
gjdABCkg.txt
ABCfg.jpg
ffABCff.exe

I would just want to replace ABC with whatever 3 letters I wanted I'm using python 3.2

I was messing around to see if I could get it to work but nothing I did was working so here's what I have so far.

import os  

directory = input ("Enter your directory")
old = input ("Enter what you want to replace ")
new = input ("Enter what you want to replace it with")

Upvotes: 3

Views: 9154

Answers (2)

shahrokh
shahrokh

Reputation: 21

import os

def rename(path,oldstr,newstr):
    for files in os.listdir(path):
        os.rename(os.path.join(path, files), os.path.join(path, files.replace(oldstr, newstr)))

using this could easily do your job

Upvotes: 0

root
root

Reputation: 80346

You probably need to add some things, but here's the basic idea:

import os

def rename(path,old,new):
    for f in os.listdir(path):
        os.rename(os.path.join(path, f), 
                  os.path.join(path, f.replace(old, new)))

EDIT: As noted @J.F Sebastian in the comments you can use relative paths from Python 3.3 (at least on a Linux machine).

From the docs:

os.replace(src, dst, *, src_dir_fd=None, dst_dir_fd=None) can support specifying src_dir_fd and/or dst_dir_fd to supply paths relative to directory descriptors.

Upvotes: 3

Related Questions