Categories
Uncategorized

Renaming Files in Directory – Python

This script will look for all the files in a directory that end with the extension .txt and change them all to .html using the rename function in the os module.

The script was written for a directory with the following structure

my_folder/
    folder_A/
        A_file_1.txt
        A_file_2.txt
        A_file_3.txt

    folder_B/
        B_file_1.txt
        B_file_2.txt
        B_file_3.txt

    ....

    folder_Z/
        Z_file_1.txt
        Z_file_2.txt
        Z_file_3.txt

Also, I am sure there is a more eficient way of getting the file name without using the re module…but I don’t know it.

Anyway, here’s the script…

from os import rename,walk,listdir
from re import sub

# walk through the folder
for root,dirs,files in walk('my_folder'):
	for str_each_folder in dirs:
		# we get the directory path
		str_the_path = '/'.join([root,str_each_folder])
		# list all the files using directory path
		for str_each_file in listdir(str_the_path):
			# look for the files we want
			if str_each_file.endswith('.txt'):
				# remove extension 
				str_txt_name = sub('.txt','',str_each_file)
				# now add the new one
				str_html_name = str_the_name+'.html'
				
				# full path for both files
				str_old_name = '/'.join([str_the_path,str_each_file])
				str_new_name = '/'.join([str_the_path,str_html_name])

				# now rename using the two above strings
				# and the full path to the files
				rename(str_old_name,str_new_name)

		# we can print the folder name so we know
		# that all files in the folder are done
		print str_each_folder

Now, all our files should look like this…

my_folder/
    folder_A/
        A_file_1.html
        A_file_2.html
        A_file_3.html

    folder_B/
        B_file_1.html
        B_file_2.html
        B_file_3.html

    ....

    folder_Z/
        Z_file_1.html
        Z_file_2.html
        Z_file_3.html

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s