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)
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.
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.
rename() method in Python is used to rename a file or directory.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With