Need to use python to convert media files to mp3 files - python-3.x

import moviepy.editor as m
import os
for i in os.listdir():
if i == ".mpeg": #How do I make that work(I know it can't, I just have it there to explain what I need)
video = m.VideoFileClip(i)
video.audio.write_audiofile(i)
Need it to sort through files, find the media ones, and change them to .mp3

Here's how I would change your code. Extract the filename and extension, use the extension to filter files and use the filename to create a new filename with the .mp3 extension. This makes sure you don't overwrite your source video file with audio.
import moviepy.editor as m
import os
for file_path in os.listdir():
filename, file_extension = os.path.splitext(file_path)
if file_extension == ".mpeg":
video = m.VideoFileClip(file_path)
audio_file_path = filename + ".mp3"
video.audio.write_audiofile(audio_file_path)

Related

Convert multiple MP3 files to WAV in python

I want to convert multiple MP3 audio files in a folder to WAV format (with mono type) using python code.
I tried the below code using pydub:
import os
from pydub import AudioSegment
audio_files = os.listdir('path')
# Folder is having audio files of both MP3 and WAV formats
len_audio=len(audio_files)
for i in range (len_audio):
if os.path.splitext(audio_files[i])[1] == ".mp3":
mp3_sound = AudioSegment.from_mp3(audio_files[i])
mp3_sound.export("<path>\\converted.wav", format="wav")
I am getting how will i export the converted wav file with different file names.
please suggest
I would do something like:
import os
from pydub import AudioSegment
path = "the path to the audio files"
#Change working directory
os.chdir(path)
audio_files = os.listdir()
# You dont need the number of files in the folder, just iterate over them directly using:
for file in audio_files:
#spliting the file into the name and the extension
name, ext = os.path.splitext(file)
if ext == ".mp3":
mp3_sound = AudioSegment.from_mp3(file)
#rename them using the old name + ".wav"
mp3_sound.export("{0}.wav".format(name), format="wav")
You can find more about the format mini language here.
This is simply just changing the extension name of multiple files
import os
from pathlib import Path
path = "the path to the audio files"
#Change working directory
os.chdir(path)
audio_files = os.listdir()
for file in audio_files:
p = Path(file)
p.rename(p.with_suffix('.wav'))

How to register .gz format in shutil.register_archive_format to use same format in shutil.unpack_archive

I have Example.json.gz and I want to unpack it or extract it in python using shutil.unpack_archive()
However it gives error shutil.ReadError: Unknown archive format as '.gz' format is not in the list of default format.
So it has to be register first using shutil.register_archive_format. Can somebody please help me register and unpack (extract it)
You should define a function that knows how to extract a gz file and then register this function. You could use the gzip library, for instance:
import os
import re
import gzip
import shutil
def gunzip_something(gzipped_file_name, work_dir):
"""gunzip the given gzipped file"""
# see warning about filename
filename = os.path.split(gzipped_file_name)[-1]
filename = re.sub(r"\.gz$", "", filename, flags=re.IGNORECASE)
with gzip.open(gzipped_file_name, 'rb') as f_in: # <<========== extraction happens here
with open(os.path.join(work_dir, filename), 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
try:
shutil.register_unpack_format('gz', ['.gz', ], gunzip_something)
except:
pass
shutil.unpack_archive("Example.json.gz", os.curdir, 'gz')
WARNING: if you extract on the same dir where your gzipped file resides and your file does not have a .gz extension I'm not sure what happens (overwrite?).

How to read specific information from .txt files in .tar file without fully unzipping it python3

I have many (like 1000) .bz2 files with each (200-50Mb) containing 4 .txt(.dat) files inside , how can I read some specific information from .txt(dat)s without decompressing them? I am only a beginner python 3 user,so please give me some hits or maybe useful examples. Thank you.
I made code which actually unzip .txt(s) in temp folder but it takes like 40sec to proceed 170Mb tar...only one...whereas I have thousands.
import bz2
import os
import tempfile
import shutil
pa = '/home/user/tar' #.tar(s) location
fds = sorted(os.listdir(pa))
i = 0
for bz in fds:
path = os.path.join(pa, tar)
i +=1
archive = bz2.BZ2File(path, 'r')
tmpdir = tempfile.mkdtemp(dir=os.getcwd())
bz2.decompress('example.txt', path=tmpdir)
path_to_my_file = os.path.join(tmpdir, 'example.txt')
here goes some simple manupulation with my .txt (like print smthg)
shutil.rmtree(tmpdir)

Python3 clip.duration of all mp4 files in a folder

I am new to Python (using Python 3.6) and would like to extract the duration (in seconds) of all mp4 files I have in one folder. Code I have is:
path2 = path_directory
from moviepy.video.io.VideoFileClip import VideoFileClip
for root, dirs, files in os.walk(path2):
for filename in files:
clip = VideoFileClip(files)
print(clip.duration)
If I define clip = VideoFileClip("name_of_one_specific_file.mp4") it correctly prints the length (i.e. 590seconds) of that specific file, so I guess the mistake is in how I walk through all the files. I would need a list of the duration for each of the 245 mp4 files I have in path2.
Thank you very much in advance.
You just have a small error:
path2 = path_directory
from moviepy.video.io.VideoFileClip import VideoFileClip
for root, dirs, files in os.walk(path2):
for filename in files:
clip = VideoFileClip(filename) # <= !!!
print(clip.duration)
You want to open filename, not files. filename is the name of one specific file, files is the list of all files in a directory.
There's a newer library, available from Python 3.4, that's generally easier to use than walk. It's pathlib.
This is how you can use it in your situation.
from pathlib import Path
from moviepy.video.io.VideoFileClip import VideoFileClip
path2 = r' -------- '
for filename in Path(path2).glob('*.mp4'):
clip = VideoFileClip(filename.as_posix())
print(clip.duration)

Custom filetype in Python 3

How to start creating my own filetype in Python ? I have a design in mind but how to pack my data into a file with a specific format ?
For example I would like my fileformat to be a mix of an archive ( like other format such as zip, apk, jar, etc etc, they are basically all archives ) with some room for packed files, plus a section of the file containing settings and serialized data that will not be accessed by an archive-manager application.
My requirement for this is about doing all this with the default modules for Cpython, without external modules.
I know that this can be long to explain and do, but I can't see how to start this in Python 3.x with Cpython.
Try this:
from zipfile import ZipFile
import json
data = json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
with ZipFile('foo.filetype', 'w') as myzip:
myzip.writestr('digest.json', data)
The file is now a zip archive with a json file (thats easy to read in again in many lannguages) for data you can add files to the archive with myzip write or writestr. You can read data back with:
with ZipFile('foo.filetype', 'r') as myzip:
json_data_read = myzip.read('digest.json')
newdata = json.loads(json_data_read)
Edit: you can append arbitrary data to the file with:
f = open('foo.filetype', 'a')
f.write(data)
f.close()
this works for winrar but python can no longer process the zipfile.
Use this:
import base64
import gzip
import ast
def save(data):
data = "[{}]".format(data).encode()
data = base64.b64encode(data)
return gzip.compress(data)
def load(data):
data = gzip.decompress(data)
data = base64.b64decode(data)
return ast.literal_eval(data.decode())[0]
How to use this with file:
open(filename, "wb").write(save(data)) # save data
data = load(open(filename, "rb").read()) # load data
This might look like this is able to be open with archive program
but it cannot because it is base64 encoded and they have to decode it to access it.
Also you can store any type of variable in it!
example:
open(filename, "wb").write(save({"foo": "bar"})) # dict
open(filename, "wb").write(save("foo bar")) # string
open(filename, "wb").write(save(b"foo bar")) # bytes
# there's more you can store!
This may not be appropriate for your question but I think this may help you.
I have a similar problem faced... but end up with some thing like creating a zip file and then renamed the zip file format to my custom file format... But it can be opened with the winRar.

Resources