Supertwister
Supertwister

Reputation: 115

Replace a substring of file name

Sorry if this question has been already asked before. I didn't find an answer by searching. In need to replace a sub string of a file name in Python.

Old String: "_ready"

New String: "_busy"

Files: a_ready.txt, b_ready.txt, c.txt, d_blala.txt, e_ready.txt

Output:a_busy.txt, b_busy.txt, c.txt, d_blala.txt, e_busy.txt

Any ideas? I tried to use replce(), but nothing happen. The files are still with the old names.

Here is my code:

import os

counter = 0

for file in os.listdir("c:\\test"):
    if file.endswith(".txt"):
        if file.find("_ready") > 0:
            counter = counter + 1
            print ("old name:" + file)
            file.replace("_ready", "_busy")
            print ("new name:" + file)
if counter == 0:
    print("No file has been found")

Upvotes: 0

Views: 16740

Answers (5)

Artjom B.
Artjom B.

Reputation: 61962

The other answer have shown you that you can replace a substring with string.replace. What you need is os.rename.

import os
counter = 0
path = "c:\\test"
for file in os.listdir(path):
    if file.endswith(".txt"):
        if file.find("_ready") > -1:
            counter = counter + 1
            os.rename(os.path.join(path, file), os.path.join(path, file.replace("_ready", "_busy")))
if counter == 0:
    print("No file has been found")

The problem with your code is that strings in python are immutable, so replace returns a new string which you have to replace the current file and add to a list if you want to use it later:

files = [] # list of tuple with old filename and new filename
for file in os.listdir(path):
    if file.endswith(".txt"):
        if file.find("_ready") > -1:
            counter = counter + 1
            newFileName = file.replace("_ready", "_busy"))
            files.append((file, newFileName))

Upvotes: 12

Selva
Selva

Reputation: 986

from os import rename, listdir

fnames = listdir('.')
for fname in fnames:
    if fname.endswith('.txt'):
        new_name = fname.replace('_ready', '_busy')
        rename(fname, new_name)

this is what you probably you need. still i dint understood you?

Upvotes: 1

Renier
Renier

Reputation: 1535

You can also do something like(if the string is constant):

old_string = "a_ready"
new_string = old_string[:1]+"_busy"

Though I think @Selva has a better way of doing it.

Upvotes: 0

Tehsmeely
Tehsmeely

Reputation: 188

string.replace() is what you seek

check it out here, it's right at the bottom

You can use

for file in files:
    output.append( file.replace(oldString, newString) )

Upvotes: 0

Selva
Selva

Reputation: 986

something like this:

old_string = "a_ready"
new_string = old_string.replace('_ready', '_busy')

Upvotes: 0

Related Questions