A script is a set of instructions written in any scripting language that helps you automate tasks or control processes.
Now that you know the basics, let’s have some practice. Assume you have around 100 files with the names “book-part-1.pdf”, “book-part-2.pdf”, …, “book-part-100.pdf”. You want to replace all the hyphens (-) in the file names with underscores (_), because the website where you’re trying to upload these documents doesn’t allow you to upload files with names containing hyphens.
import os
# Replace "-" with "_" in file names
directory = "/path/to/your/folder"
for filename in os.listdir(directory):
if "-" in filename:
old_path = os.path.join(directory, filename)
new_filename = filename.replace("-", "_")
new_path = os.path.join(directory, new_filename)
os.rename(old_path, new_path)
print(f"Renamed: {filename} -> {new_filename}")
import os
...\> REM Replace "-" with "_" in file names
directory = "/path/to/your/folder"
for filename in os.listdir(directory):
if "-" in filename:
old_path = os.path.join(directory, filename)
new_filename = filename.replace("-", "_")
new_path = os.path.join(directory, new_filename)
os.rename(old_path, new_path)
print(f"Renamed: {filename} -> {new_filename}")
To find all files in the directory, we have to use the listdir method from the os package.
Then we check if the file name contains a - in the next line. In such a case, we find the current path (old_path) of the file by merging the directory and its file name. We can create the new file name by replacing the - with _ using the replace method.
We then generate the new file path (new_path) in the similar way we generate the old_path. Finally, we call the rename method in os package with old and new file paths as arguments.
Replace /path/to/your/folder with the actual directory containing the files.
Run the script in the corresponding environment:
Save as a .py file (for example: script.py), then execute with python script.py
May 30, 2025