Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)
like image 373
FaCoffee Avatar asked Jul 26 '16 17:07

FaCoffee


People also ask

Does renaming a file change the extension?

Though you can rename many files to switch their file extension, most will “break” when you do so. This is typically because the file type is specific to a certain code-format. In those cases you will have to use file conversion like in the case of changing SVG image files to JPG or PNG.

How do I get the filename extension in Python?

We can use Python os module splitext() function to get the file extension. This function splits the file path into a tuple having two values - root and extension.

Which method of os module is used to rename a file?

rename() method in Python is used to rename a file or directory.


1 Answers

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)
like image 151
Suever Avatar answered Sep 29 '22 00:09

Suever