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


Messages In This Thread
Rename only first 4 characters of filename - by bmatt8 - Nov-15-2018, 03:40 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Rename part of filename in multiple files atomxkai 7 7,380 Feb-18-2022, 10:03 PM
Last Post: atomxkai
  Rename Multiple files in directory to remove special characters nyawadasi 9 6,450 Feb-16-2021, 09:49 PM
Last Post: BashBedlam
  How to rename a CSV file by adding MODIFIED in the filename? Python_User 25 8,187 Dec-13-2020, 12:35 PM
Last Post: Larz60+
  Remove escape characters / Unicode characters from string DreamingInsanity 5 13,795 May-15-2020, 01:37 PM
Last Post: snippsat
  Group files according to first few characters in filename python_newbie09 7 4,743 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