A friend was trying to open files with Korean names and was finding that Windows 7 was giving him errors. There were well over 22,000 files to deal with, and he did not want to rename them all individually. As a result, this program was quickly written to help him in renaming his vast assortment of files and folders so that he could easily open them in his resource viewer application.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | import os
import sys
def main():
program = os.path.abspath(sys.argv[0])
# Get the current working directory and
# walk through it and its subdirectories.
cwd = os.getcwd()
for root, dirs, files in os.walk(cwd, False):
# Rename all of the folders.
for index, name in enumerate(dirs):
old_name = os.path.join(root, name)
new_name = os.path.join(root, str(index))
rename(old_name, new_name)
# Rename all of the files.
for index, name in enumerate(files):
old_name = os.path.join(root, name)
if old_name != program:
name, ext = os.path.splitext(name)
name_ext = '{}{}'.format(index, ext)
new_name = os.path.join(root, name_ext)
rename(old_name, new_name)
def rename(old, new):
try:
os.rename(old, new)
except:
print('Could not rename:', old)
if __name__ == '__main__':
main()
|
Tags: rename