Rename only first 4 characters of filename - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Rename only first 4 characters of filename (/thread-14122.html) |
Rename only first 4 characters of filename - bmatt8 - Nov-15-2018 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)) RE: Rename only first 4 characters of filename - ichabod801 - Nov-15-2018 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. RE: Rename only first 4 characters of filename - nilamo - Nov-15-2018 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. |