Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change multiple filenames in a directory using Python

I am learning Python and I have been tasked with:

  • adding "file_" to the beginning of each name in a directory
  • changing the extension (directory contains 4 different types currently: .py, .TEXT, .rtf, .text)

I have many files, all with different names, each 7 characters long. I was able to change the extensions but it feels very clunky. I am positive there is a cleaner way to write the following (but its functioning, so no complaints on that note):

    import os, sys
    path = 'C:/Users/dana/Desktop/text_files_2/'
        for filename in os.listdir(path):
            if filename.endswith('.rtf'):
                newname = filename.replace('.rtf', '.txt')
                os.rename(filename, newname)
        elif filename.endswith('.py'):
                newname = filename.replace('.py', '.txt')
                os.rename(filename, newname)
        elif filename.endswith('.TEXT'):
                newname = filename.replace('.TEXT', '.txt')
                os.rename(filename, newname)
        elif filename.endswith('.text'):
               newname = filename.replace('.text', '.txt')
               os.rename(filename, newname)

I do still have a bit of a problem:

  1. the script currently must be inside my directory for it to run.
  2. I can not figure out how to add "file_" to the start of each of the filenames [you would think that would be the easy part]. I have tried declaring newname as

    newname = 'file_' + str(filename)
    

    it then states filename is undefined.

Any assistance on my two existing issues would be greatly appreciated.

like image 424
Dana Scott Avatar asked Jan 23 '16 06:01

Dana Scott


2 Answers

The basic idea would be first get the file extension part and the real file name part, then put the filename into a new string.

os.path.splitext(p) method will help to get the file extensions, for example: os.path.splitext('hello.world.aaa.txt') will return ['hello.world.aaa', '.txt'], it will ignore the leading dots.

So in this case, it can be done like this:

import os
import sys

path = 'C:/Users/dana/Desktop/text_files_2/'

for filename in os.listdir(path):
    filename_splitext = os.path.splitext(filename)
    if filename_splitext[1] in ['.rtf', '.py', '.TEXT', '.text']:
        os.rename(os.path.join(path, filename), 
                os.path.join(path, 'file_' + filename_splitext[0] +  '.txt'))
like image 103
Evan Avatar answered Oct 13 '22 19:10

Evan


Supply the full path name with os.path.join():

os.rename(os.path.join(path, filename), os.path.join(name, newname))

and you can run your program from any directory.

You can further simply your program:

extensions = ['.rtf', '.py', '.TEXT', '.text']
for extension in extensions:
     if filename.endswith(extension):
         newname = filename.replace(extension, '.txt')
         os.rename(os.path.join(path, filename), os.path.join(path, newname))
         break

All the other elif statements are not needed anymore.

like image 26
Mike Müller Avatar answered Oct 13 '22 17:10

Mike Müller