Xonshiz
Xonshiz

Reputation: 1367

how to rename file in a directory using python

I have a file named "x.mkv" in a folder named "export". X could be anything.. it's not named exactly X, it's just file with some name. I want to rename the file to "Movie1 x [720p].mkv". I want to keep the file's original name and add Movie1 as prefix and [720p] as a suffix. There is just one file in the folder, nothing more. How do I do so? I tried using variables in os.rename and i failed.. this is what I used :

import os
w = os.listdir("C:/Users/UserName/Desktop/New_folder/export")
s = '[Movie1]' + w + '[720p]'
os.rename(w,s)

What I'm trying to do is... get the file name from the folder, as there is and will be only 1 file, so, this seems appropriate. saving the fetch results in 'w' and then using another variable 's' and adding prefix and suffix. Then at the end, I fail at using the variables in 'os.rename' command.

Upvotes: 1

Views: 2822

Answers (2)

khammel
khammel

Reputation: 2127

Your original won't work for a few reasons:

  1. os.listdir() returns a list and not a string so your string concatenation will fail.
  2. os.rename() will have trouble renaming the file unless the path is given or you change the cwd.

I'd suggest the following code:

import os
path="C:/Users/UserName/Desktop/New_folder/export/"
w = os.listdir(path)
#since there is only one file in directory it will be first in list
#split the filename to separate the ext from the rest of the filename
splitfilename=w[0].split('.')
s = '[Movie1]' + '.'.join(splitfilename[:-1]) + '[720p].'+splitfilename[-1]
os.rename(path+w[0],path+s)

Upvotes: 2

Sam Estep
Sam Estep

Reputation: 13354

Use os.rename:

def my_rename(path, name, extension, prefix, suffix):
    os.rename(path + '/' +          old_name          + '.' + extension,
              path + '/' + prefix + old_name + suffix + '.' + extension)

my_rename('/something/export', 'x', 'mkv', 'Movie1 ', ' [720p]')

Upvotes: 0

Related Questions