pythoncsvfile-extensionfile-rename

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)

Solution

  • 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)