Python3 clip.duration of all mp4 files in a folder - python-3.x

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)

Related

Need to use python to convert media files to mp3 files

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)

how to rename files in a folder using pathlib in python?

I need help renaming .jpg files in my folder with the same prefix, 'cat_'. for example, 070.jpg should be renamed cat_070.jpg.
the files are located within the Cat folder:
from pathlib import Path
p = Path('C:\\Users\\me\\Jupiter_Notebooks\\Dataset\\Train\\Cat\\')
so I dont quite see how to do it? the below is wrong because it does not 'look into' the files in this directory.
p.rename(Path(p.parent, 'cat_' + p.suffix))
I have also unsuccessfully tried this:
import os
from os import rename
from os import listdir
# Get path
cwd = "C:\\Users\\me\\Jupiter_Notebooks\\Dataset\\Train\\Cat"
# Get all files in dir
onlyfiles = [f for f in listdir(cwd) if isfile(join(cwd, f))]
for file in onlyfiles:
# Get the current format
if file[-4:]==(".jpg"):
s = file[1]
# Change format and get new filename
s[1] = 'cat'
s = '_'.join(s)
# Rename file
os.rename(file, s)
print(f"Renamed {file} to {s}")
FileNotFoundError: [WinError 3] The system cannot find the path specified: 'C:\\Users\\me\\Jupiter_Notebooks\\Dataset\\Train\\Cat\\'
how can I do it? sorry I'm really a beginner here.
How about:
from pathlib import Path
img_dir = Path('C:\\Users\\me\\Jupiter_Notebooks\\Dataset\\Train\\Cat\\') # path to folder with images
for img_path in img_dir.glob('*.jpg'): # iterate over all .jpg images in img_dir
new_name = f'cat_{img_path.stem}{img_path.suffix}' # or directly: f'cat_{img_path.name}'
img_path.rename(img_dir / new_name)
print(f'Renamed `{img_path.name}` to `{new_name}`')
pathlib also supports renaming files, so the os module is not even needed here.
use pathlib. Path. iterdir() to rename all files in a directory
1) for path in pathlib. Path("a_directory"). iterdir():
2) if path. is_file():
3) old_name = path. stem. original filename.
4) old_extension = path. suffix. original file extension.
5) directory = path. parent. ...
6) new_name = "text" + old_name + old_extension.
7) path. rename(pathlib.

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'))

FileNotFoundError long file path python - filepath longer than 255 characters

Normally I don't ask questions, because I find answers on this forum. This place is a goldmine.
I am trying to move some files from a legacy storage system(CIFS Share) to BOX using python SDK. It works fine as long as the file path is less than 255 characters.
I am using os.walk to pass the share name in unix format to list files in the directory
Here is the file name.
//dalnsphnas1.mydomain.com/c$/fs/hdrive/home/abcvodopivec/ENV Resources/New Regulation Review/Regulation Reviews and Comment Letters/Stormwater General Permits/CT S.W. Gen Permit/PRMT0012_FLPR Comment Letter on Proposed Stormwater Regulations - 06-30-2009.pdf
I also tried to escape the file, but still get FileNotFoundError, even though file is there.
//dalnsphnas1.mydomain.com/c$/fs/hdrive/home/abcvodopivec/ENV Resources/New Regulation Review/Regulation Reviews and Comment Letters/Stormwater General Permits/CT S.W. Gen Permit/PRMT0012_FLPR\ Comment\ Letter\ on\ Proposed\ Stormwater\ Regulations\ -\ 06-30-2009.pdf
So I tried to shorten the path using win32api.GetShortPathName, but it throws the same FileNotFoundError. This works fine on files with path length less than 255 characters.
Also tried to copy the file using copyfile(src, dst) to another destination folder to overcome this issue, and still get the same error.
import os, sys
import argparse
import win32api
import win32con
import win32security
from os import walk
parser = argparse.ArgumentParser(
description='Migration Script',
)
parser.add_argument('-p', '--home_path', required = True, help='Home Drive Path')
args = vars(parser.parse_args())
if args['home_path']:
pass
else:
print("Usage : script.py -p <path>")
print("-p <directory path>/")
sys.exit()
dst = (args['home_path'] + '/' + 'long_file_path_dir')
for dirname, dirnames, filenames in os.walk(args['home_path']):
for filename in filenames:
file_path = (dirname + '/' + filename)
path_len = len(file_path)
if(path_len > 255):
#short_path = win32api.GetShortPathName(file_path)
copyfile(file_path, dst, follow_symlinks=True)
After a lot of trial and error, figured out the solution (thanks to stockoverflow forum)
switched from unix format to UNC path
Then appending each file generated through os.walk with r'\\?\UNC' like below. UNC path starts with two backward slashes, I have to remove one to make it to work
file_path = (r'\\?\UNC' + file_path[1:])
Thanks again for everyone who responded.
Shynee

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)

Resources