Reputation: 127
I'm trying to use the os module for the first time to rename multiple files at once. However, it seems I have to specify the file type. Otherwise, the file can't be opened anymore. It becomes like this:
But can I do it without specifying the filetype? How do I do that?
My current code when I don't specify it is this
import os
option = input("\nRename files in current directory? Yes or no: ").lower()
if (option == "yes"):
path = os.getcwd()
else:
path = os.chdir(input("\nEnter directory: "))
name = input("\nEnter new filename: ")
i = 0
for source in os.listdir(path):
destination =name + str(i)
os.rename(source, destination)
i += 1
Thank you for your help!
Upvotes: 0
Views: 127
Reputation: 19372
os.rename
does not care about extensions ("file types", as you call them), but Windows does. If there is no extension, Windows does not know what the file is.
You can extract the extension of the file before renaming and append it to the new name.
You can use os.path.splitext
to get the original extension:
old_name, extension = os.path.splitext(old_filename)
new_filename = new_name + extension
os.rename(old_filename, new_filename)
In your case:
for i, source in enumerate(os.listdir(path)):
old_name, extension = os.path.splitext(source)
destination = name + str(i) + extension
os.rename(source, destination)
Upvotes: 3
Reputation: 47
This is about the file extension. The extension is used by Windows to select the application to use for opening that file.
Without an extension, Windows could not select which program to use. But if you open the file with the correct program, you will not have any issue.
Upvotes: -1