Hi!

I'm about to rename a hole bunch of files in different folders and want to use Python to do it. The problem is that I want to keep parts of the file name from the old file and insert it into the new file in another location.

for example:

old file: abcXXabc

new file: XXdefghi

Where the XX is the part I want to keep; always numbers. XX is'nt always on the same location in the old file. Any suggestions on how to do this?

I'm a newb when it comes to Python but heard it was great to use for these types of problems and maybe i can become more skilld afterwards!

this is what I got so far..

directory = '.'
for file in os.listdir('directory'):
re.search('([0-9]+)', file).group(1)
if '&' in file :
os.rename(file, file.replace('abcabc', 'defghi'))

Greatly appreciate it! /MCl

>>> s="abc123abc"
>>> t= "".join([x for x in s if x.isdigit()]+[x for x in s if not x.isdigit()])
>>> print t
123abcabc
>>>

This was the quickest I got in my mind.

Try not to use regular expression. They are quite slow.

thanks! although, at another forum I i recieved this code (thanks E.T) but it doesnt handle file extensions.. does anyone got suggestions on how to solve that? (I got several file types that needs to be renamed..)

import os
import re
pattern = re.compile(r"abc(\d+)abc")
tree = os.walk("/path/to/ur/dir")
targets = []
for dirpath, dirnames, names in tree:    
for name in names:
        m = pattern.match(name)
        if m:
                newname = os.path.join(dirpath, "%sdfghij" % m.group1))                
                os.rename(os.path.join(dirpath, name), newname)

If you just want to replace certain extensions, you can use something like this:

file_list = [
'list_nonunique1.py',
'Gene_read1.pyw',
'wx_psutil1.pyw',
'pa16names.txt',
'wxFrame_centerthings1.pyw',
'averagewords1.py',
'oneline.txt',
'tk_coinflip.pyw']

# replace extension .pyw with .py
new_list= []
for fname in file_list:
    if '.pyw' in fname:
        fname = fname[:-3] + 'py'
    new_list.append(fname)
    print(fname)

"""
my result -->
list_nonunique1.py
Gene_read1.py
wx_psutil1.py
pa16names.txt
wxFrame_centerthings1.py
averagewords1.py
oneline.txt
tk_coinflip.py
"""

A third option, if you want to keep the extension.

old_file_name = 'bc13abc2.txt'

## This assumes there is only one "." in the file name
substrs = old_file_name.split(".")
print substrs
## then use siddhant3s' example to find the digits, or some way
## using isdigit() and add substrs[1] (the ending) to that name.
digits_list = [x for x in old_file_name if x.isdigit()]
print digits_list

## which is the same as
second_list = []
for x in old_file_name:
   if x.isdigit()
      second_list.append(x)

## you then have to .join into a string

Thank you woooee and Sneekula for all the help!

I still got some issues though. I dont want to specify the old file name since I got a great number of files with different file names and want to change the syntax on all of them. I was'nt very clear on what had to be done and aplgz for this..

for example:

old files:
1. abcde22ab.txt
2. abcde23ab.jpg

and also

3. fghij22fg.txt
4. fghij23fg.jpg

..and want the new files to look like this:

1. 22KLMNO.txt
2. 23KLMNO.jpg

and also

3. 22PQRST.txt
4. 23PQRST.jpg

That is, I want to keep the number in the file name and put in first in the new file name, I want to be able to specify which letters that should be in the new file (for fghik, replace with PQRST in another location of the string) and also to keep the extension of the original file. I would greatly appreciate any help and tips on how to solve this! /MCl

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.