How can you rename a file in Python?
a) By using the os.rename() function
b) By using the shutil.move() function
c) By using the file.rename() method
d) By using the os.chdir() function
Answer:
a) By using the os.rename() function
Explanation:
To rename a file in Python, you use the os.rename()
function, which is part of the os
module. This function takes two arguments: the current file name and the new file name.
import os
# Example of renaming a file
os.rename("old_name.txt", "new_name.txt")
In this example, the file old_name.txt
is renamed to new_name.txt
using the os.rename()
function.
Renaming files is a common operation when managing files programmatically, such as when organizing files, changing file extensions, or updating file names based on content.