Python: how to retain the file extension when renaming files with os?
Asked Answered
P

2

8

Say I have a folder with n csv files which I want to rename. The new filename is going to be something like ABxxxx, with xxxx being a progressive number from 1 to 1000.

While doing this, how can I retain the original file extension, which is csv?

What I have done so far has changed the filenames but has pruned away the extension:

directory=r'C:\Me\MyDir'
subdir=[x[0] for x in os.walk(directory)]
subdir.pop(0)

for i in subdir:
    temp_dir=r''+i
    os.chdir(temp_dir)
    a='A'
    b='B'
    for file in glob.glob("*.csv"):
        for i in range(1,1001):
           newname=a+b+i
        os.rename(file,newname)
Pardoes answered 26/7, 2016 at 17:38 Comment(3)
Add .csv to newname?Thanet
Like newname+".csv"?Pardoes
get the last four characters of the filename - ext = filename[-4:], assign it to a variable, use that variable to construct a new filename.Gluey
T
20

You can simply append '.csv' to your new filename:

os.rename(file, newname + '.csv')

In general (for any file type), a better way to do this would be to get the existing extension first using os.path.splitext and then append that to the new filename.

oldext = os.path.splitext(file)[1]
os.rename(file, newname + oldext)
Thanet answered 26/7, 2016 at 17:39 Comment(1)
can you also help with: #78327923Nimwegen
S
1

Use os.path.splitext to build a tuple of (basepath, extension) and enumerate to generate your "uniquifier". Now you can just use vanilla string formatting to glue it together

for i in subdir:
    temp_dir=r''+i
    os.chdir(temp_dir)
    a='A'
    b='B'
    for idx, file in enumerate(glob.glob("*.csv")):
        os.rename(file,'{0}{2}{1}'.format(*(os.path.splitext(file) + (idx,))))
Sandhurst answered 26/7, 2016 at 17:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.