Prasanth G
Prasanth G

Reputation: 93

renaming filenames to integer sequence in python3

I need to rename filenames in a folder containing many text files. The renaming should follow the sequence of numbers for every file. It should be like as follows:

***given files***     ***renamed files***
abc.txt              1.txt
def.txt              2.txt
rsd.txt              3.txt
ijb.txt              4.txt

the above files are in a folder named data

my code is like this

import glob 
import os
file=sorted(glob.glob("/home/prasanth/Desktop/project/prgms/dt/details/*.txt"))
fp=[]
for b in file:
    fp.append(b)
i=1
for f in fp:
    n=f.replace('.html','')
    n=n.replace('.htm','')
    m=n.replace(n,str(i)+'.txt')
    i=i+1
    os.rename(f,m)

my problem is the files after renaming are moving into the folder where the python code is written.but i need the renamed files in the same folder in which they are present before

Upvotes: 2

Views: 2061

Answers (1)

Christian König
Christian König

Reputation: 3570

Great, so what have you tried?

As a starting point, have a look at the os-module, especially os.walk() and os.rename().

EDIT:

Your files are moved, because you replace the whole path with the number with m=n.replace(n,str(i)+'.txt'). This renames subfolder\textfile.txt to be renamed to 1.txt, which moves the file to the current directory as a side effect.

Also I am not sure what you try to achieve with the htm(l)-replaces, since afterwards you replace everything with your number.

Additionally, you don't need to build a copy of the list of txt-files and afterwards iterate over it, you can do it directly on the original file list.

So this could probably work for you:

import glob
import os

filelist=sorted(glob.glob("/home/prasanth/Desktop/project/prgms/dt/details/*.txt"))
i=1

for oldname in filelist:
    # ignore directories
    if os.path.isfile(oldname):
        # keep original path
        basepath=os.path.split(oldname)[0]
        newname=os.path.join(basepath, "{}.txt".format(str(i)))
        i=i+1
        print("Renaming {} to {}".format(oldname, newname))
        os.rename(oldname, newname)

Side note: the rename will fail when a file with the new file name already exists. You should probably handle that with try ... except.

Upvotes: 1

Related Questions