0

I just want to know how can I change the name of mp4 video using python. I tried looking on the internet but could not find it. I am a beginner in python

2 Answers2

1

you can use os module to rename as follows... import os os.rename('full_file_path_old','new_file_name_path)

Aniket singh
  • 118
  • 1
  • 6
1

So firstly let's take an example to make things clear. Let's suppose you downloaded a playlist from YouTube which follows the following naming C++ Tutorial Setting IDE #1.mp4 and so on...

Now when this will be saved in your computer it will be in alphabetical order and will be tough for you to watch them in proper order.

So now we know the problem let's solve it with our code and you can modify it according to your convenience.

import os

os.chdir('D:\YouTube\C++')

for f in os.listdir():
    f_name, f_ext = os.path.splitext(f)
    f_title, f_num = f_name.split('#')
    
    f_title=f_title.strip()
    f_num=f_num.strip()

    new_name= '{}. {}{}'.format(f_num, f_title, f_ext)
    os.rename(f, new_name)

Now let me explain the code to you line by line:

  1. import os is the module we are including to use os.rename and other functions which can be found here [https://docs.python.org/3/library/os.html][1]
  2. os.chdir is used to change your directory to the one which contains all your video files.
  3. Then we run a for loop to go through each and every file using os.listdir which will simply list all the files in our current directory.
  4. Now we use os.path.splitext(f)it splits our path name from its extension. So now f_name = 'C++ Tutorial Setting IDE #1' and f_ext = .mp4
  5. Now we will use split on our f_name as show and now what this will do is it will separate strings use # as delimiter. Now f_title = C++ Tutorial Setting IDE and f_num = 1
  6. Now both f_title and f_num may have unwanted spaces which can be removed by using simple strip.
  7. Now we will use some string formatting and save the final name in new_name here i have use three curly braces to format my string to look something like this 1. C++ Tutorial Setting IDE.mp4

So I hope this helps.

PS. For more info you can watch this video https://youtu.be/ve2pmm5JqmI

Nishant
  • 11
  • 4