import os
import fnmatch


for l in os.listdir("C:\Bilder"):
    if fnmatch.fnmatch(l, 'IMG*'):
        l.replace(l, "HH")
        print l

I am trying soemthing like this, but it is not working.
Can anybody help me?

Cheers

I don't like l as variable name (looks too much like number one), so I changed it a little:

import os
import fnmatch


for fn in os.listdir("C:/Bilder"):
    print fn  # test
    if fnmatch.fnmatch(fn, 'IMG*'):
        fn = fn.replace(fn, "HH")
        print fn

"""my result -->
IMG100_0015.jpg
HH
"""

I don't like l as variable name (looks too much like number one), so I changed it a little:

import os
import fnmatch


for fn in os.listdir("C:/Bilder"):
    print fn  # test
    if fnmatch.fnmatch(fn, 'IMG*'):
        fn = fn.replace(fn, "HH")
        print fn

"""my result -->
IMG100_0015.jpg
HH
"""

Hello, thank you for your answer. I did not expalin exactly what I wanted to do in this little code-snippet.
I actually want to rename all files in the directory "C:\\Bilder" with the name IMG to HH.
But the example you showed me did not do that.
Is it possible for you to show me how to do that?
Thank You
Cheers

What is the full name,and what should the new full name be?,you most explain better.
IMG.jpg to HH.jpg?
HH1.jpg HH2.jpg....?

What is the full name,and what should the new full name be?,you most explain better.
IMG.jpg to HH.jpg?
HH1.jpg HH2.jpg....?

Yes, I need to expalin better, but I have also extended my code

import os
import fnmatch

count = 0 
while (count < 1):
    for fn in os.listdir("C:/Bilder"):
        print fn  # test
        if fnmatch.fnmatch(fn, 'IMG*'):
            fn = fn.replace(fn, "Bilde" + str(count) + ".JPG")
            int(count)
            count = count + 1
            print fn

As you see I want to use the increment 'count' as part of the filename.

From IMG_1361.JPG to Bilde1.JPG, Bilde2,JPG and so forth.

I am not sure if the fn.replace permanently renames my files. Should I use rename or soemthing?

Should I use rename or soemthing?

Yes you can try this.

import os
import fnmatch

for i,fn in enumerate(os.listdir("C:/Bilder")):
    if fnmatch.fnmatch(fn, 'IMG*'):
        os.rename(os.path.join('C:/Bilder', fn), os.path.join('C:/Bilder','Bilde%d.jpg' % i))

Yes you can try this.

import os
import fnmatch

for i,fn in enumerate(os.listdir("C:/Bilder")):
    if fnmatch.fnmatch(fn, 'IMG*'):
        os.rename(os.path.join('C:/Bilder', fn), os.path.join('C:/Bilder','Bilde%d.jpg' % i))

Thank you, it is working.
Cheers

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.