3

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.

1
  • You can split the file name according to "_", convert to a number and add trailing zeros. Then join it again using "_".join(splitted_name). Commented May 8, 2017 at 9:12

4 Answers 4

4

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))
Sign up to request clarification or add additional context in comments.

1 Comment

a_test.txt would be converted to 00a_text.txt
1

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'

2 Comments

I have some files with multiple underscores. In this case its chopping-off all characters after the second underscore. How to mention only to consider first underscore?
I was afraid of the same thing, should've already taken that into account. I've updated the answer to include the fix. Please test it out and let me know if it works. Thanks!
0

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)

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.