kevin kevin - 4 years ago 138
Python Question

Rename file names in a folder - Python

I have files in a folder. Their names look like:

hello_1
music
hello_2
music_2015


I would like to rename them sequentially:

1
2
3
4


My python script is:

import glob, os

n = 1
for filename in glob.glob('data\*'):
os.rename(filename, str(n))
n += 1


I am getting the following error:

[Error 183] Cannot create a file when that file already exists

Answer Source

Try this version:

import os
data = os.path.abspath("data/")
for i, f in enumerate(os.listdir(data)):
    src = os.path.join(data, f)
    dst = os.path.join(data, (str(i + 1)))
    os.rename(src, dst)

It's using normalized absolute paths. It works for me. It's kind of more concise and requires only os library instead of two.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download