3
Python script.

import os
[os.rename(f, f.replace('', 'xyz_')) for f in os.listdir('.') 
if not f.startswith('.')]

from above script i want to rename the files as Before

1.0.1.0.html
1.20.0.0.html
1.11.1.0.html
1.10.1.0.html

after renaming,

xyz_1.0.1.0.html
xyz_1.20.0.0.html
xyz_1.11.1.0.html
xyz_1.10.1.0.html

Is it possible,can anyone help me out.

1
  • os.rename(f, 'xyz_' + f) ?? Commented Jun 10, 2015 at 9:10

2 Answers 2

6

You can use glob to find all the html files:

from glob import glob
import os
pre = "xyz_"
[os.rename(f, "{}{}".format(pre, f)) for f in glob("*.html")]

html files starting with a . should be ignored as glob treats filenames beginning with a dot (.) as special cases..

def glob(pathname):
    """Return a list of paths matching a pathname pattern.

    The pattern may contain simple shell-style wildcards a la
    fnmatch. However, unlike fnmatch, filenames starting with a
    dot are special cases that are not matched by '*' and '?'
    patterns.

    """
    return list(iglob(pathname))
Sign up to request clarification or add additional context in comments.

Comments

0

Try -

import os
[os.rename(f, 'xyz_' + str(f)) for f in os.listdir('.') 
if ((not f.startswith('.')) and f.endswith(".html"))]

3 Comments

it is replacing also with other extensions, but i want only .html files should be replaced
Edited to include that.
Thanks Buddy But if i want to replace any text with new filename,in this there is not a option, as in my code,there is find what option and replace with is . can you add this option in it please. for example. "xyz_1.0.2.html" rename as "abc_1.0.2.html"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.