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
Asked
Active
Viewed 816 times
0
-
is this a file on your local computer? does it have to be in python? why not just `mv old.mp4 new.mp4`? – Pablo Fernandez Feb 23 '20 at 14:45
-
4Does this answer your question? [How to rename a file using Python](https://stackoverflow.com/questions/2491222/how-to-rename-a-file-using-python) – Pablo Fernandez Feb 23 '20 at 14:46
2 Answers
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
-
Thanks it worked. can you also tell me how can I get the names of the all video one by one in a folder using for loop? – Muhammad Ahmed Feb 23 '20 at 16:06
-
use os.listdir("location_of_folder") this function return a list of all file to the specified location. – Aniket singh Feb 23 '20 at 19:49
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:
import os
is the module we are including to useos.rename
and other functions which can be found here [https://docs.python.org/3/library/os.html][1]os.chdir
is used to change your directory to the one which contains all your video files.- 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. - Now we use
os.path.splitext(f)
it splits our path name from its extension. So nowf_name = 'C++ Tutorial Setting IDE #1'
andf_ext = .mp4
- 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. Nowf_title = C++ Tutorial Setting IDE
andf_num = 1
- Now both
f_title
andf_num
may have unwanted spaces which can be removed by using simple strip. - 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 this1. 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