Python Forum
Rename only first 4 characters of filename
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Rename only first 4 characters of filename
#1
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))
Reply
#2
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Rename part of filename in multiple files atomxkai 7 7,213 Feb-18-2022, 10:03 PM
Last Post: atomxkai
  Rename Multiple files in directory to remove special characters nyawadasi 9 6,232 Feb-16-2021, 09:49 PM
Last Post: BashBedlam
  How to rename a CSV file by adding MODIFIED in the filename? Python_User 25 7,903 Dec-13-2020, 12:35 PM
Last Post: Larz60+
  Remove escape characters / Unicode characters from string DreamingInsanity 5 13,420 May-15-2020, 01:37 PM
Last Post: snippsat
  Group files according to first few characters in filename python_newbie09 7 4,594 Aug-02-2019, 06:34 AM
Last Post: cvsae

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020