Created
August 31, 2016 14:23
-
-
Save dehamzah/4ffac06ce522bc4d4572890bf35fbd68 to your computer and use it in GitHub Desktop.
Program for prefix and suffix number in file names in targeted folder
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
# Program for prefix and suffix number in file names in targeted folder | |
import os | |
import random | |
# Set target directory where the files resides | |
target_dir = r"/Users/darthmako/Documents/playground/udacity-python-foundation/secret-messages" | |
''' | |
r stands for rawpack. it means to tell python take this string as it is. | |
it will benefit you if you are in windows environment. | |
learn more: http://stackoverflow.com/questions/2081640/what-exactly-do-u-and-r-string-flags-do-in-python-and-what-are-raw-string-l | |
''' | |
def rename_files(): | |
# Save current directory path | |
saved_path = os.getcwd() | |
# Change to target directory where the files resides | |
os.chdir(target_dir) | |
# Get all file names | |
file_lists = os.listdir(target_dir) | |
# Iterate each file | |
for file_name in file_lists: | |
# Get filename and extensions | |
name, ext = os.path.splitext(file_name) | |
# Add any number on file_name | |
new_name = str(random.randint(1, 1000)) + name + str(random.randint(100, 10000)) + ext | |
# Rename the file | |
os.rename(file_name, new_name) | |
print "File renamed: %s -> %s" % (file_name, new_name) | |
# Back to previous directory | |
os.chdir(saved_path) | |
# Run the function | |
rename_files() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment