How to change the name of a mp4 video using python - python

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

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

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 use os.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 now
f_name = 'C++ Tutorial Setting IDE #1' and f_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. Now f_title = C++ Tutorial Setting IDE and f_num = 1
Now both f_title and f_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 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

Related

open image files from window explorer using python code

i recently just took up python for my research studentship (so i don't have a very strong cs background). I'm dealing with a large set of image files in many different subfolders in a big folder so I want to build a python code to search and open them.
I got introduced to os and sys libraries to play around with them. I could get the file to open but that is only when I specifically put a full dirpath for the file. I'm having trouble building a code to direct python to the right folder when I only know the folder name(i'm not sure if i'm making sense haha sorry).
My goal is to be able to type the id name of a folder containing the image in the python output so the file could be pulled out and displayed.
Any suggestions would be great! thank you so much!
You should look at the documentation for the functions we recommended you in the comments. Also, you may be interested to read some tutorials on files and directory, mainly in Python.
And look at how many questions we had to ask you to understand what you wanted to do. Provide code. Explain clearly what is your input, its type, its possible values, and what is the expected output.
Anyway, from what I understood so far, here is a proposal based on os.startfile :
import os
from pathlib import Path
# here I get the path to the desired directory from user input, but it could come from elsewhere
path_to_directory = Path(input("enter the path to the folder : "))
extension_of_interest = ".jpg"
filepaths_of_interest = []
for entry in path_to_directory.iterdir():
if entry.is_file() and entry.name.endswith(extension_of_interest):
print("match: " + str(entry))
filepaths_of_interest.append(entry)
else:
print("ignored: " + str(entry))
print("now opening ...")
for filepath_of_interest in filepaths_of_interest:
os.startfile(filepath_of_interest, "open")
when run, given the path C:/PycharmProjects/stack_oveflow/animals, it prints :
enter the path to the folder : C:/PycharmProjects/stack_oveflow/animals
ignored: C:\PycharmProjects\stack_oveflow\animals\cute fish.png
match: C:\PycharmProjects\stack_oveflow\animals\cute giraffe.jpg
match: C:\PycharmProjects\stack_oveflow\animals\cute penguin.jpg
match: C:\PycharmProjects\stack_oveflow\animals\cute_bunny.jpg
now opening ...
and the 3 jpg images have been opened with my default image viewer.
The startfile function was asked to "open" the file, but there are other possibilities described in the documentation.

Os.path gives unexpected output

lately I started working with the Os module in python . And I finally arrived to this Os.path method . So here is my question . I ran this method in one of my kivy project just for testing and it actually didn't returned the correct output.The method consisted of finding if any directory exist and return a list of folders in the directory . otherwise print Invalid Path and return -1 . I passed in an existing directory and it returned -1 but the weird path is that when I run similar program out of my kivy project using the same path present in thesame folder as my python file it return the desired output .here is the image with the python file and the directory name image I have tested which returns invalid path.
and here is my code snippet
def get_imgs(self, img_path):
if not os.path.exists(img_path):
print("Invalid Path...")
return -1
else:
all_files = os.listdir(img_path)
imgs = []
for f in all_files:
if (
f.endswith(".png")
or f.endswith(".PNG")
or f.endswith(".jpg")
or f.endswith(".JPG")
or f.endswith(".jpeg")
or f.endswith(".JPEG")
):
imgs.append("/".join([img_path, f]))
return imgs
It's tough to tell without seeing the code with your function call. Whatever argument you're passing must not be a valid path. I use the os module regularly and have slowly learned a lot of useful methods. I always print out paths that I'm reading or where I'm writing before doing it in case anything unexpected happens, I can see that img_path variable, for example. Copy and paste the path in file explorer up to the directory and make sure that's all good.
Some other useful os.path methods you will find useful, based on your code:
os.join(<directory>, <file_name.ext>) is much more intuitive than imgs.append("/".join([img_path, f]))
os.getcwd() gets your working directory (which I print at the start of scripts in dev to quickly address issues before debugging). I typically use full paths to play it safe because Python pathing can cause differences/issues when running from cmd vs. PyCharm
os.path.basename(f) gives you the file, while os.path.dirname(f) gives you the directory.
It seems like a better approach to this is to use pathlib and glob. You can iterate over directories and use wild cards.
Look at these:
iterating over directories: How can I iterate over files in a given directory?
different file types: Python glob multiple filetypes
Then you don't even need to check whether os.path.exists(img_path) because this will read the files directly from your file system. There's also more wild cards in the glob library such as * for anything/any length, ? for any character, [0-9] for any number, found here: https://docs.python.org/3/library/glob.html

How can I read files with similar names on python, rename them and then work with them?

I've already posted here with the same question but I sadly I couldn't come up with a solution (even though some of you guys gave me awesome answers but most of them weren't what I was looking for), so I'll try again and this time giving more information about what I'm trying to do.
So, I'm using a program called GMAT to get some outputs (.txt files with numerical values). These outputs have different names, but because I'm using them to more than one thing I'm getting something like this:
GMATd_1.txt
GMATd_2.txt
GMATf_1.txt
GMATf_2.txt
Now, what I need to do is to use these outputs as inputs in my code. I need to work with them in other functions of my script, and since I will have a lot of these .txt files I want to rename them as I don't want to use them like './path/etc'.
So what I wanted was to write a loop that could get these files and rename them inside the script so I can use these files with the new name in other functions (outside the loop).
So instead of having to this individually:
GMATds1= './path/GMATd_1.txt'
GMATds2= './path/GMATd_2.txt'
I wanted to write a loop that would do that for me.
I've already tried using a dictionary:
import os
import fnmatch
dict = {}
for filename in os.listdir('.'):
if fnmatch.fnmatch(filename, 'thing*.txt'):
examples[filename[:6]] = filename
This does work but I can't use the dictionary key outside the loop.
If I understand correctly, you try to fetch files with similar names (at least a re-occurring pattern) and rename them. This can be accomplished with the following code:
import glob
import os
all_files = glob.glob('path/to/directory/with/files/GMAT*.txt')
for file in files:
new_path = create_new_path(file) # possibly split the file name, change directory and/or filename
os.rename(file, new_path)
The glob library allows for searching files with * wildcards and makes it hence possible to search for files with a specific pattern. It lists all the files in a certain directory (or multiple directories if you include a * wildcard as a directory). When you iterate over the files, you could either directly work with the input of the files (as you apparently intend to do) or rename them as shown in this snippet. To rename them, you would need to generate a new path - so you would have to write the create_new_path function that takes the old path and creates a new one.
Since python 3.4 you should be using the built-in pathlib package instead of os or glob.
from pathlib import Path
import shutil
for file_src in Path("path/to/files").glob("GMAT*.txt"):
file_dest = str(file_src.resolve()).replace("ds", "d_")
shutil.move(file_src, file_dest)
you can use
import os
path='.....' # path where these files are located
path1='.....' ## path where you want these files to store
i=1
for file in os.listdir(path):
if file.endswith(end='.txt'):
os.rename(path + "/" + file, path1 + "/"+str(i) + ".txt")
i+=1
it will rename all the txt file in the source folder to 1,2,3,....n.txt

Renaming/copying in windows python

I am trying to copy and rename some PDFs with absolute paths.
ie: c:\users\andrew\pdf\p.pdf gets copied to c:\users\pdf\ORGp.pdf
Leaving two files in the directory p.pdf and ORGp.pdf
I've been working on this issue for the past hour and I can't seem to nail it.
Is there a more pythonic way to do it then splitting the string into a list and rejoining them after adding ORG on the last element?
Using python 2.7 on windows 8.
Your question is a bit ambiguous, but I will try to answer it anyway.
This is a python code sample that will copy under the new names, all files under a particular folder, specified at the beginning of the script:
import os
import shutil
folder_name = "c:\\users\\andrew\\pdf"
for root_folder, _, file_names in os.walk(folder_name):
for file_n in file_names:
new_name = os.path.join(root_folder, "ORG" + file_n)
old_name = os.path.join(root_folder, file_n)
print "We will copy at ", new_name, old_name
shutil.copyfile(old_name, new_name)
This code will copy and rename a list of absolute file paths:
import os
import shutil
files_to_rename = ["c:\\users\\andrew\\pdf\\p.pdf", "c:\\users\\andrew\\pdf2\\p2.pdf"]
for file_full_path in files_to_rename:
folder_n, file_n = os.path.split(file_full_path)
new_name = os.path.join(folder_n, "ORG" + file_n)
print "We will copy at ", new_name, file_full_path
shutil.copyfile(file_full_path, new_name)
I testing this script on Mac OS, with Python 2.7.7, but I think it should work nicely also on Windows.
You can try
import os
.......some logic.....
os.rename(filename, newfilename)
Splitting the string into a list and rejoining (after removing 'andrew' from the list and prefixing 'ORG' to the last element) is quite Pythonic. It's an explicit and obvious way to do it.
You can use the standard str and list methods to do it. However, there are various dedicated file path manipulation functions in the os.path module which you should become familiar with, but the str and list methods are fine when you are sure that all the file names you're processing are sane. os.path also has other useful file-related functions: you can check if a file exists, whether it's a file or a directory, get a file's timestamps, etc.
To actually copy the file once you've generated the new name, use shutil.copyfile(). You may also wish to check first that the file doesn't already exist using os.path.exists(). Unfortunately, some metadata gets lost in this process, eg file owners, as mentioned in the warning in the shutil docs.
This is what I ended up doing to do the rename. I'm not sure how pythonic it is, but it works.
split=fle.split('\\')
print split
pdf=split[len(split)-1]
pdf='ORG%s' % pdf
print pdf
del split[len(split)-1]
split.append(pdf)
fle1 = '\\'.join(split)
try:
shutil.copy(fle, fle1)
except:
print('failed copy')
return''

Problem reading text files without extensions in python

I have written a piece of a code which is supposed to read the texts inside several files which are located in a directory. These files are basically text files but they do not have any extensions.But my code is not able to read them:
corpus_path = 'Reviews/'
for infile in glob.glob(os.path.join(corpus_path,'*.*')):
review_file = open(infile,'r').read()
print review_file
To test if this code works, I put a dummy text file, dummy.txt. which worked because it has extension. But i don't know what should be done so files without the extensions could be read.
can someone help me? Thanks
Glob patterns don't work the same way as wildcards on the Windows platform. Just use * instead of *.*. i.e. os.path.join(corpus_path,'*'). Note that * will match every file in the directory - if that's not what you want then you can revise the pattern accordingly.
See the glob module documentation for more details.
Just use * instead of *.*.
The latter requires an extension to be present (more precisely, there needs to be a dot in the filename), the former doesn't.
You could search for * instead of *.*, but this will match every file in your directory.
Fundamentally, this means that you will have to handle cases where the file you are opening is not a text file.
it seems that you need
from os import listdir
from filename in ( fn for fn in listdir(corpus_path) if '.' not in fn):
# do something
you could write
from os import listdir
for fn in listdir(corpus_path):
if '.' not in fn:
# do something
but the former with a generator spares one indentation level

Categories

Resources