13

How can I rename the following files:

abc_2000.jpg
abc_2001.jpg
abc_2004.jpg
abc_2007.jpg

into the following ones:

year_2000.jpg
year_2001.jpg
year_2004.jpg
year_2007.jpg

The related code is:

import os
import glob
files = glob.glob('abc*.jpg')
for file in files:
    os.rename(file, '{}.txt'.format(???))
poke
  • 369,085
  • 72
  • 557
  • 602

7 Answers7

17
import os
import glob
files = glob.glob('year*.jpg')
for file in files:
    os.rename(file, 'year_{}'.format(file.split('_')[1]))

The one line can be broken to:

for file in files:
    parts = file.split('_') #[abc, 2000.jpg]
    new_name = 'year_{}'.format(parts[1]) #year_2000.jpg
    os.rename(file, new_name)
zhangyangyu
  • 8,520
  • 2
  • 33
  • 43
  • 1
    thank you. but could you please break down complex code into simpler one so that a newbie could understand? –  Jul 19 '13 at 14:18
  • what does parts[1] mean? –  Jul 19 '13 at 14:25
  • You see parts is a list. For `abc_2000.jpg` parts is `[abc, 2000.jpg]`. So parts contains two elements. We can access the elements by index(counting from 0). So `parts[1]` access the second elements in parts, in this case `2000.jpg`.@guava – zhangyangyu Jul 19 '13 at 14:27
4

Because I have done something similar today:

#!/usr/bin/env python

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, f))]

    for infile in infiles:
        outfile = re.sub(r'abc', r'year' , infile)
        os.rename(os.path.join(indir, infile), os.path.join(indir, outfile))
Schoenix
  • 191
  • 1
  • 4
0

Here is my solution which is written with comments for each step so that even a newbie can understand and use, hack, and customize:

https://github.com/JerusalemProgramming/PythonAutomatedRenamingOfFilenames/blob/master/program_FileRenameJPEGS.py

## THIS PYTHON FILE NEEDS TO BE RUN WITHIN THE IMAGES FOLDER WITH JPG/JPEG IMAGES WHOSE
## ..FILENAMES NEED RENAMED TO NUMERICAL SEQUENCE (1.jpg, 2.jpg, 3.jpg, 4.jpg... etc.)

## IMPORT MODULES
## IMPORT MODULES
## IMPORT MODULES

import re, glob, os, pathlib

## BEGIN DEFINE FUNCTIONS
## BEGIN DEFINE FUNCTIONS
## BEGIN DEFINE FUNCTIONS

def fn_RenameFiles(files, pattern, replacement):

    ## DECLARE VARIABLES
    ## SET COUNTER FOR LATER USE
    i = 1

    ## BEGIN FOR LOOP
    ## BEGIN FOR LOOP
    ## BEGIN FOR LOOP

    ## FOR EACH PATHNAME IN 
    for pathname in glob.glob(files):

        ## PATHNAME
        #print("pathname =", pathname) ## TEST OUTPUT

        ## BASENAME
        basename = os.path.basename(pathname)
        #print("basename =", basename) ## TEST OUTPUT

        ## IF PATHNAME EQUALS BASENAME...
        if pathname == basename:

            ##...THEN TEST OUTPUT - THIS SHOULD ALWAYS PRINT TRUE
            print("pathname == basename:  TRUE")
            print("pathname string =", pathname) ## STRING FILENAME IN DIRECTORY
            print("basename string =", basename) ## STRING FILENAME IN DIRECTORY

        ## ELSE IF PATHNAME DOES NOT EQUAL BASENAME...
        else:

            ##...THEN TEST OUTPUT
            print("pathname == basename:  FALSE")
            print("pathname string =", pathname) ## STRING FILENAME IN DIRECTORY
            print("basename string =", basename) ## STRING FILENAME IN DIRECTORY

        ## CALCULATE NEW FILENAME WITH REGULAR EXPRESSIONS   
        NewFilename = re.sub(pattern, replacement, basename)

        ## TEST OUTPUT
        print("NewFilename =", NewFilename)


        ## IF NEWFILENAME DOES NOT EQUAL BASENAME...
        if NewFilename != basename:

            ##...THEN RENAME THE PATHNAME WITH NEWFILENAME
            os.rename(pathname, os.path.join(os.path.dirname(pathname), NewFilename))

        ## ELSE DOES THIS CONDTION EVER GET TRIGGERED?
        else:
            print("DOES THIS CONDITION EVER GET TRIGGERED?")


    ## END FOR LOOP
    ## END FOR LOOP
    ## END FOR LOOP

    ## TEST OUTPUT - LIST OF FILENAMES IN DIRECTORY
    print("glob.glob(files) =", glob.glob(files))


    ## BEGIN FOR LOOP
    ## BEGIN FOR LOOP
    ## BEGIN FOR LOOP

    ## FOR EACH FILE IN glob.glob(files)
    for each in glob.glob(files):

    ## FILE PATH TO DIRECTORY OF IMAGES
        ## FILE PATH OF CURRENT WORKING DIRECTORY WITH IMAGES = e.g. C:\RootFolder\images
        filepath = os.path.abspath('') ## = os.getcwd()

        ## TEST OUTPUT - FILE PATH OF CURRENT WORKING DIRECTORY
        print("FILE PATH OF CURRENT WORKING DIRECTORY =", filepath)

        ## RENAME FILES IN CWD; JOIN EMPTY STRING FILEPATH + STRING OF INTEGER OF CURRENT COUNTER + STRING OF .JPG 
        os.rename(os.path.join(filepath, each), os.path.join(filepath, str(i)+'.jpg'))

        ## INCREASE COUNTER
        i = i+1

    ## END FOR LOOP
    ## END FOR LOOP
    ## END FOR LOOP

    ## TEST OUTPUT - LIST OF FILENAMES IN DIRECTORY
    print("glob.glob(files) =", glob.glob(files))

    ## TEST OUTPUT - GAME OVER
    print("GAME OVER.  GO CHECK YOUR IMAGE FOLDER")


## END DEFINE FUNCTIONS
## END DEFINE FUNCTIONS
## END DEFINE FUNCTIONS

### BEGIN MAIN PROGRAM
### BEGIN MAIN PROGRAM
### BEGIN MAIN PROGRAM


## CALL FUNCTION        
fn_RenameFiles("*.jpg", r"^(.*)\.jpg$", r"new(\1).jpg")

### END MAIN PROGRAM
### END MAIN PROGRAM
### END MAIN PROGRAM

## GAME OVER

## WE HOPE YOU ENJOYED AND THAT THIS HELPS YOUR UNDERSTANDING OF USING PYTHON LANGUAGE TO SOLVE PROBLEMS WITH PYTHON PROGRAMMING
## PLEASE COME BACK AGAIN SOON
## PLEASE VISIT OUR WEB SITES (OUR PROBLEM-SOLVING PROGRAMMING, CODING, & DEVELOPMENT SERVICES ARE AVAILABLE FOR HIRE):
## www.JerusalemProgrammer.com
## www.JerusalemProgrammers.com
## www.JerusalemProgramming.com
0

# By changing one line in code i think this line will work or may be without changing anything this will work

import glob2
import os


def rename(f_path, new_name):
    filelist = glob2.glob(f_path + "*.ma")
    count = 0
    for file in filelist:
        print("File Count : ", count)
        filename = os.path.split(file)
        print(filename)
        new_filename = f_path + new_name + str(count + 1) + ".ma"
        os.rename(f_path+filename[1], new_filename)
        print(new_filename)
        count = count + 1

Call the function by passing two arguments f_path as your path and new_name as you like to give to file.

Farhana Naaz Ansari
  • 7,524
  • 26
  • 65
  • 105
0

This allows to rename the file with the creation date_time.

import os, datetime, time

folder = r"*:\***\***\TEST"

for file in os.listdir(folder):
    date = os.path.getmtime(os.path.join(folder, file))
    new_filename = datetime.datetime.fromtimestamp(date).strftime("%Y%m%d_%H%M%S.%f")[:-4]
    os.rename(os.path.join(folder, file), os.path.join(folder, new_filename + ".pdf"))
    print("Renamed " + file + " to " + new_filename)
    time.sleep(0.1)
Dima
  • 1
  • This is not at all what the asker asked. By the looks of it, this will rename a file to its creation date, while the question was about renaming more than one file. I.e. nothing to do with dates, even though the example files happens to be years. – Artog Aug 26 '19 at 12:49
0
import os
import glob

path = 'C:\\Users\\yannk\\Desktop\\HI'
file_num = 0
for filename in glob.glob(os.path.join(path, '*.jpg')):
    os.rename(filename, path + '\\' + str(file_num) + '.jpg')
    file_num += 1

This is to rename all files in a folder to the indentation of their position in the folder you should be able to scrap this code up and use it for your purpose. THIS is for people who are on windows and therefore os.cwd or os.getcwd do not work

Yann Kull
  • 51
  • 5
0

check if any files exists with the new_name. if no file exists then continue renaming file.

for file in files:
    parts = file.split('_') # Existing file name
    new_name = 'year_{}'.format(parts[1]) #New file to be written
    if not os.path.exists(new_name):
        os.rename(file, new_name)
Lohith
  • 866
  • 1
  • 9
  • 25