rcubefather
rcubefather

Reputation: 1564

How to add numbers infront of each files without touching filename using Python?

I have some files (800+) in folder as shown below:

test_folder
    1_one.txt
    2_two.txt
    3_three.txt
    4_power.txt
    5_edge.txt
    6_mobile.txt
    7_test.txt
    8_power1.txt
    9_like.txt
    10_port.txt
    11_fire.txt
    12_water.txt

I want to rename all these files using python like this:

test_folder
    001_one.txt
    002_two.txt
    003_three.txt
    004_power.txt
    005_edge.txt
    006_mobile.txt
    007_test.txt
    008_power1.txt
    009_like.txt
    010_port.txt
    011_fire.txt
    012_water.txt

Can we do this with Python? Please guide on how to do this.

Upvotes: 3

Views: 2234

Answers (4)

Martin Evans
Martin Evans

Reputation: 46759

You can use glob.glob() to get a list of text files. Then use a regular expression to ensure that the file being renamed starts with digits and an underscore. Then split the file up and add leading zeros as follows:

import re
import glob
import os

src_folder = r"c:\source folder"    

for filename in glob.glob(os.path.join(src_folder, "*.txt")):
    path, filename = os.path.split(filename)
    re_file = re.match("(\d+)(_.*)", filename)

    if re_file:
        prefix, base = re_file.groups()
        new_filename = os.path.join(path, "{:03}{}".format(int(prefix), base))
        os.rename(filename, new_filename)

The {:03} tells Python to zero pad your number to 3 digits. Python's Format Specification Mini-Language is very powerful.

Note os.path.join() is used to safely concatenate path components, so you don't have to worry about trailing separators.

Upvotes: 0

degant
degant

Reputation: 4981

Using zfill:

Split based on underscore _ and then use zfill to pad zero's

import os

os.chdir("test_folder")
for filename in os.listdir("."):
    os.rename(filename, filename.split("_")[0].zfill(3) + filename[filename.index('_'):])

Converting to integer:

Only renames if prefix is a valid integer. Uses format(num, '03') to make sure the integer is padded with appropriate leading zero's. Renames files 1_file.txt, 12_water.txt but skips a_baa.txt etc.

import os

os.chdir("E:\pythontest")
for filename in os.listdir("."):
    try:
        num = int(filename.split("_")[0])
        os.rename(filename, format(num, '03') + filename[filename.index('_'):])
    except:
        print 'Skipped ' + filename

EDIT: Both snippets ensure that if the filename contains multiple underscores then the later ones aren't snipped. So 1_file_new.txt gets renamed to 001_file_new.txt.

Examples:

# Before
'1_one.txt', 
'12_twelve.txt', 
'13_new_more_underscores.txt', 
'a_baaa.txt',  
'newfile.txt',  
'onlycharacters.txt'

# After
'001_one.txt',  
'012_twelve.txt',  
'013_new_more_underscores.txt',  
'a_baaa.txt',  
'newfile.txt',  
'onlycharacters.txt'

Upvotes: 1

Himanshu dua
Himanshu dua

Reputation: 2523

Use zfill to pad zeros

import os,glob

src_folder = r"/user/bin/"
for file_name in glob.glob(os.path.join(src_folder, "*.txt")):
  lst = file_name.split('_')
  if len(lst)>1:
    try:
        value=int(lst[0])
    except ValueError:
        continue
    lst[0] = lst[0].zfill(3)
    os.rename(file_name, '_'.join(lst))

Upvotes: 4

Brian Sidebotham
Brian Sidebotham

Reputation: 1906

Here's a quick example to rename the files in the current directory:

import os

for f in os.listdir("."):
    if os.path.isfile(f) and len(f.split("_")) > 1:
        number, suffix = f.split("_")
        new_name = "%03d_%s" % (int(number), suffix)
        os.rename(f, new_name)

Upvotes: 0

Related Questions