Python Forum

Full Version: Rename only first 4 characters of filename
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Im trying to rename only the first 4 characters of a filename.

Example: rename a045av18.c00 to paav18.c00

The "av18" will change each day so i just want to replace "a045" with "pa" and thats it.

Having a hard time getting this to work. I tried a rename with DOS commands but it doesnt work with a wildcard.


import os
import sys
import re

if __name__ == "__main__":
    _, indir = sys.argv

    infiles = [f for f in os.listdir(indir) if os.path.isfile(os.path.join(indir

    for infile in infiles:
        outfile = re.sub(r'pa', r'a045' , infile)
        os.rename(os.path.join(indir, infile), os.path.join(indir, outfile))
If you just want to replace the first four characters with 'pa', use:

outfile = 'pa' + infile[4:]
Also, line 8 in your posted code is incomplete.
As far as I know, operating systems don't support partial renames. So renaming just the first part of a file name doesn't make sense. "renaming" a file also doesn't necessarily mean anything, as it's normally just an abstraction over "moving" a file, and you can't move a file without having the full name of the new file.

So instead of thinking about how to change the first 4 characters of a name, try instead to think about changing the file name. From one string, to a different string. From there, all you need to think about is basic string slicing (as ichabod801 demonstrated) to get the new string.