I am on a project that trims video at specific time ,then converts it to an audio file and save it.
But the problem is i cannot get every Newly created audio file with a specific name that is stored inside a .txt file
Here's the Code
from moviepy.editor import *
import shutil
s= open("begin.txt") #Starting time
lines1 = s.readlines()
e = open("end.txt") #End Time
lines2 = e.readlines()
t = open("title.txt") #The text file which contain the file name
lines3 = t.readlines()
print("Starting...")
for x in range(1776): #Iam triming the video files to 1777 parts
st=lines1[x]
en=lines2[x]
t=lines3[x]
print("Start Time: "+st)
print("End Time: "+en)
video = VideoFileClip("J:\Movie\SM.mp4").subclip(st, en)
video.audio.write_audiofile("J:\Movie\ audio.mp3")
shutil.move("J:\Movie\ audio.mp3","J:\Movie\Data\ "+t+".mp3")
I have tried using both shutil.move and os.rename but both produce the same Error
Here's the Output:
Starting...
Start Time: 39.33
End Time: 41.958
MoviePy - Writing audio in J:\Movie\ audio.mp3
Traceback (most recent call last):
File "C:\Users\CRPSM\Anaconda3\lib\shutil.py", line 563, in move
os.rename(src, real_dst)
OSError: [WinError 123] The filename, directory name, or volume label syntax
is incorrect: 'J:\\Marvel\\ audio.mp3' -> 'J:\\Marvel\\Data\\ Things are
never
gonna bethe same now\n.mp3'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:/Users/CRPSM/PycharmProjects/AC#/venv/fdsh.py", line 27, in <module>
shutil.move("J:\Marvel\ audio.mp3","J:\Marvel\Data\ "+t+".mp3")
File "C:\Users\CRPSM\Anaconda3\lib\shutil.py", line 577, in move
copy_function(src, real_dst)
File "C:\Users\CRPSM\Anaconda3\lib\shutil.py", line 263, in copy2
copyfile(src, dst, follow_symlinks=follow_symlinks)
File "C:\Users\CRPSM\Anaconda3\lib\shutil.py", line 121, in copyfile
with open(dst, 'wb') as fdst:
OSError: [Errno 22] Invalid argument: 'J:\\Marvel\\Data\\ Things are never
gonna bethe same now\n.mp3'
MoviePy - Done.
Process finished with exit code 1
1: You have an indentation error for the for-loop.
2: You should remove the '\n', which stands for newline, from each file name in you list:
from moviepy.editor import *
import shutil
s= open("begin.txt") #Starting time
lines1 = [l.strip() for l in s.readlines()]
e = open("end.txt") #End Time
lines2 = [l.strip() for l in e.readlines()]
t = open("title.txt") #The text file which contain the file name
lines3 = [l.strip() for l in t.readlines()]
print("Starting...")
for x in range(1776): #Iam triming the video files to 1777 parts
st=lines1[x]
en=lines2[x]
t=lines3[x]
print("Start Time: "+st)
print("End Time: "+en)
video = VideoFileClip("J:\Movie\SM.mp4").subclip(st, en)
video.audio.write_audiofile("J:\Movie\ audio.mp3")
shutil.move("J:\Movie\ audio.mp3","J:\Movie\Data\ "+t+".mp3")
Related
This is my code in python for my file sorter and i dont know why it dont work
import os
import shutil
path = str(input("Enter the path you want to sort: "))
def moveFile(path):
path1 = path
path = os.listdir(path)
for file in path:
if file.endswith(".gif") or file.endswith(".jfif") or file.endswith(".jpg") or file.endswith(".jpeg") or file.endswith(".png"):
shutil.move(f"{path1}\\{file}", "C:\\Users\\CLEMENT.LAPORTE\\Pictures\\Pictures\\")
break
elif file.endswith(".mp4") or file.endswith(".mkv") or file.endswith(".avi"):
shutil.move(f"{path1}\\{file}", "C:\\Users\\CLEMENT.LAPORTE\\Videos\\Videos\\")
break
elif file.endswith(".mp3") or file.endswith(".wav") or file.endswith(".m4a"):
shutil.move(f"{path1}\\{file}", "C:\\Users\\CLEMENT.LAPORTE\\Music\\Songs\\")
break
elif file.endswith(".exe"):
shutil.move(f"{path1}\\{file}", "C:\\Users\\CLEMENT.LAPORTE\\App\\")
break
elif file.endswith(".txt") or file.endswith(".docx") or file.endswith(".pptx") or file.endswith(".pdf"):
shutil.move(f"{path1}\\{file}", "C:\\Users\\CLEMENT.LAPORTE\\Work\\")
break
elif file.endswith(".py") or file.endswith(".c") or file.endswith(".cpp") or file.endswith(".java") or file.endswith(".js") or file.endswith(".html") or file.endswith(".css"):
shutil.move(f"{path1}\\{file}", "C:\\Users\\CLEMENT.LAPORTE\\Code\\")
break
else:
shutil.move(file, "C:\\Users\\CLEMENT.LAPORTE\\Other\\")
break
print(f"Moved:\t{file}\t")
moveFile(path)
Here is my error
Enter the path you want to sort: C:\Document
Traceback (most recent call last):
File "C:\Tools\python\Portable_Python-3.9.9 x64\App\Python\lib\shutil.py", line 815, in move
os.rename(src, real_dst)
FileNotFoundError: [WinError 2] Le fichier spécifié est introuvable: 'chrome_100_percent.pak' -> 'C:\\Users\\CLEMENT.LAPORTE\\Other\\chrome_100_percent.pak'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\CLEMENT.LAPORTE\PycharmProjects\file-filter\sorter.py", line 33, in <module>
moveFile(path)
File "C:\Users\CLEMENT.LAPORTE\PycharmProjects\file-filter\sorter.py", line 29, in moveFile
shutil.move(file, "C:\\Users\\CLEMENT.LAPORTE\\Other\\")
File "C:\Tools\python\Portable_Python-3.9.9 x64\App\Python\lib\shutil.py", line 835, in move
copy_function(src, real_dst)
File "C:\Tools\python\Portable_Python-3.9.9 x64\App\Python\lib\shutil.py", line 444, in copy2
copyfile(src, dst, follow_symlinks=follow_symlinks)
File "C:\Tools\python\Portable_Python-3.9.9 x64\App\Python\lib\shutil.py", line 264, in copyfile
with open(src, 'rb') as fsrc:
FileNotFoundError: [Errno 2] No such file or directory: 'chrome_100_percent.pak'
This is the entire error message. I dont know why it dont works but i did it with a folder with 1 picture inside of it and my program worked. But when y tried with a folder with different type of file inside of it it dont work.
Can someone help me please ?
(ps: some text are in french sorry)
It's unclear how the code shown can result in that error.
This kind of code should be "table driven" which results in less code and more extensibility.
Something like this:
from glob import glob
from os.path import join, isfile
from shutil import move
from pathlib import Path
BASE = 'C:\\Users\\CLEMENT.LAPORTE'
DEFAULT = 'Other'
CONTROL = {('gif', 'jfif', 'jpg', 'jpeg', 'png'): 'Pictures\\Pictures',
('mp4', 'mkv', 'avi'): 'Videos\\Videos',
('mp3', 'wav', 'm4a'): 'Music\\Songs',
('exe',): 'App',
('txt', 'docx', 'pptx', 'pdf'): 'Work',
('py', 'c', 'cpp', 'java', 'js', 'html', 'css'): 'Code'}
def moveFiles(path):
for file in glob(join(path, '*.*'):
suffix = Path(file).suffix[1:]
for k, v in CONTROL.items():
if suffix in k:
p = v
break
else:
p = DEFAULT
try:
move(file, join(BASE, p))
print(f"Moved: {file} -> {p}")
except Exception as e:
print(f'Failed to move {file} -> {p} due to {e}')
path = input("Enter the path you want to sort: ")
moveFiles(path)
Change the \\ in the paths with / and it should normally work, if not, the specified files do not exist (try to either change them or add a condition that create a folder if t doesn't find it)
def morse_audio( item ):
from pyglet import media
import pyglet
import time
import glob
import os
import wave
from contextlib import closing
files = []
audios = []
for file in glob.glob('C:\\Users\\MQ\'s Virual World\\Downloads\\Morse\\*.wav'):
ass = str(os.path.join('C:\\Users\MQ\'s Virual World\\Downloads\\Morse', file))
print (ass)
files.append(ass)
#audio = media.load(files[1])
#audio.play()
#print (len(files))
one = list(item)
str_list = [x.strip(' ') for x in one]
str_list = [x.strip('/') for x in str_list]
for s in str_list[0]:
if s != "-" and s != ".":
list(item)
for letter in item:
for i in range(0, 51):
if letter == " ":
time.sleep(1.5)
audios.append("noise3.wav")
break
if letter != letterlst[i] and letter != letterlst[i].lower():
continue
else:
print (files[i])
audio = media.load(files[i])
audio.play()
audios.append(files[i])
audios.append("noise2.wav")
time.sleep(1)
else:
lst = item.split()
print (' '.join(lst))
for code in lst:
for i in range(0, 51):
if code == "/":
time.sleep(1.5)
audios.append("noise3.wav")
break
if code != morse[i]:
continue
else:
print (files[i])
audio = media.load(files[i])
audio.play()
audios.append(files[i])
audios.append("noise2.wav")
time.sleep(1)
break
outfile = "sounds.wav"
data= []
for file in audios:
w = wave.open(file, 'rb')
lol = w.getparams()
print (lol)
data.append( [w.getparams(), w.readframes(w.getnframes())] )
w.close()
with closing(wave.open(outfile, 'wb')) as output:
# find sample rate from first file
with closing(wave.open(audios[0])) as w:
output.setparams(w.getparams())
# write each file to output
for audioo in audios:
with closing(wave.open(audioo)) as w:
output.writeframes(w.readframes(w.getnframes()))()))
So this code previously worked but I wanted to use different file types other then .wav files but because that worked so poorly I went back to .wav. These are different .wav files but the ones that worked before get the same error message. Which is:
Traceback (most recent call last):
File "C:\Users\MQ's Virual World\AppData\Local\Programs\Python\Python35-32\morsecode.py", line 187, in <module>
morse_audio("0123456789ÁÄ#&':,$=!-().+?;/_")
File "C:\Users\MQ's Virual World\AppData\Local\Programs\Python\Python35-32\morsecode.py", line 96, in morse_audio
audio.play()
File "C:\Users\MQ's Virual World\AppData\Local\Programs\Python\Python35-32\lib\site-packages\pyglet\media\__init__.py", line 473, in play
player.play()
File "C:\Users\MQ's Virual World\AppData\Local\Programs\Python\Python35-32\lib\site-packages\pyglet\media\__init__.py", line 1012, in play
self._set_playing(True)
File "C:\Users\MQ's Virual World\AppData\Local\Programs\Python\Python35-32\lib\site-packages\pyglet\media\__init__.py", line 993, in _set_playing
self._create_audio_player()
File "C:\Users\MQ's Virual World\AppData\Local\Programs\Python\Python35-32\lib\site-packages\pyglet\media\__init__.py", line 1083, in _create_audio_player
self._audio_player = audio_driver.create_audio_player(group, self)
File "C:\Users\MQ's Virual World\AppData\Local\Programs\Python\Python35-32\lib\site-packages\pyglet\media\drivers\directsound\__init__.py", line 502, in create_audio_player
return DirectSoundAudioPlayer(source_group, player)
File "C:\Users\MQ's Virual World\AppData\Local\Programs\Python\Python35-32\lib\site-packages\pyglet\media\drivers\directsound\__init__.py", line 184, in __init__
None)
File "C:\Users\MQ's Virual World\AppData\Local\Programs\Python\Python35-32\lib\site-packages\pyglet\com.py", line 125, in <lambda>
self.method.get_field()(self.i, self.name)(obj, *args)
File "_ctypes/callproc.c", line 920, in GetResult
OSError: [WinError -2147024809] The parameter is incorrect
I've tried .wav files that used to work. It works when I use a .ogg file. Also works with mp3s. Seems only .wav files are giving it issues. Very suddenly and randomly.
I'm trying to convert a FASTQ (generated from a Illumina Miseq mate paired genome sequence) file to FASTA and eventually convert that to Genbank using an annotated reference sequence. I'm following instrucitons from the Biopython Tutorial. Here's my code and error.
from Bio import SeqIO
records = SeqIO.parse("~/Users/ryanjhope/Documents/PhD/DNA_Sequences/Genome/C. aceto_∆pyrE_∆bcd_Deepseq/YZ1_S11_L001_R1_001.fastq", "fastq")
count = SeqIO.write(records, "~/Users/ryanjhope/Documents/PhD/DNA_Sequences/Genome/C. aceto_∆pyrE_∆bcd_Deepseq/∆bcdpseudo.fasta", "fasta")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/ryanjhope/Documents/anaconda/lib/python2.7/site-packages/Bio/SeqIO/__init__.py", line 468, in write
with as_handle(handle, mode) as fp:
File "/Users/ryanjhope/Documents/anaconda/lib/python2.7/contextlib.py", line 17, in __enter__
return self.gen.next()
File "/Users/ryanjhope/Documents/anaconda/lib/python2.7/site-packages/Bio/File.py", line 90, in as_handle
with open(handleish, mode, **kwargs) as fp:
IOError: [Errno 2] No such file or directory: '~/Users/ryanjhope/Documents/PhD/DNA_Sequences/Genome/C. aceto_\xe2\x88\x86pyrE_\xe2\x88\x86bcd_Deepseq/\xe2\x88\x86bcdpseudo.fasta'
The traceback is your friend:
IOError: [Errno 2] No such file or directory: '~/Users/ryanjhope ...
and further up:
File "/Users/ryanjhope/Documents/anaconda/lib/python2.7/site-packages/Bio/File.py", line 90, in as_handle
This is '~/Users/ vs. '/Users/`
Changes these lines:
records = SeqIO.parse("~/Users/ryanjhope/Documents/PhD/DNA_Sequences/Genome/C. aceto_∆pyrE_∆bcd_Deepseq/YZ1_S11_L001_R1_001.fastq", "fastq")
count = SeqIO.write(records, "~/Users/ryanjhope/Documents/PhD/DNA_Sequences/Genome/C. aceto_∆pyrE_∆bcd_Deepseq/∆bcdpseudo.fasta", "fasta")
into:
records = SeqIO.parse("/Users/ryanjhope/Documents/PhD/DNA_Sequences/Genome/C. aceto_∆pyrE_∆bcd_Deepseq/YZ1_S11_L001_R1_001.fastq", "fastq")
count = SeqIO.write(records, "/Users/ryanjhope/Documents/PhD/DNA_Sequences/Genome/C. aceto_∆pyrE_∆bcd_Deepseq/∆bcdpseudo.fasta", "fasta")
and try again.
I'm using python 2.7
Here is my code to parse files in a folder
import linecache
import glob
path = r"G:\test\folder1"
Key = '''testresult="NOK"'''
Files = glob.glob(path+'\*.xml')
for FileName in Files:
Loop_Count = 1
while Loop_Count!= 50:
Line_Read = linecache.getline(FileName, Loop_Count)
if (Key in Line_Read):
a = FileName.split('\\')
b = len(a)-1
print a[b]
break
elif(Loop_Count == 49):
pass
Loop_Count = Loop_Count+1
print "Completed"
if folder1 has many files, i'm getting memory error
Traceback (most recent call last):
File "C:\Users\whoKnows\Desktop\test_Check111.py", line 10, in <module> Line_Read = linecache.getline(FileName, Loop_Count)
File "C:\Python27\lib\linecache.py", line 14, in getline
lines = getlines(filename, module_globals)
File "C:\Python27\lib\linecache.py", line 40, in getlines
return updatecache(filename, module_globals)
File "C:\Python27\lib\linecache.py", line 128, in updatecache
lines = fp.readlines()
MemoryError
I think its because i'm opening all the files for reading and i'm not closing them. Can anyone please tell me how to close the files While using glob.
MemoryError means you have run out of memory. You are probably loading all the files into the memory at once. Try deleting lines not needed anymore with linecache.clearcache().
I downloaded Brive which downloads your Google Docs using the Drive API. I'm running into issues with the filename not saving if it has slashes and crashes the application. How can I modify the model.py file to rewrite / as _?
model.py
brive.py
I think I just need to rewrite the "file_name" or "path" on line 74.
backend.py:
def save(self, user, document):
self._mkdir(user.login)
prefix = self._root_dir + user.login + os.sep
for file_name, content in document.contents.items():
path = prefix + file_name
Log.debug(u'Writing {}\'s {} to {}'.format(
user.login, document.title, path
))
f = open(path, 'w')
f.write(content)
f.close()
This is the error:
[ 2013-01-17 T 06:17:08 Z ] Saving coral.lopez's doc "Lunchbox Monster High 4/7/12" (id: 1GyiuKFZeargO8KfzKS5H9V3PVbgTJufw2PwLaILzRVw)
[ 2013-01-17 T 06:17:08 Z ] Unexpected shutdown, deleting /home/davidneudorfer/google_docs_backup/2013-01-17T061021Z/ folder
### Unexpected error when saving coral.lopez's documents (doc id: 1GyiuKFZeargO8KfzKS5H9V3PVbgTJufw2PwLaILzRVw) ###
Traceback (most recent call last):
File "brive.py", line 114, in <module>
main()
File "brive.py", line 92, in main
user.save_documents(backend)
File "/home/davidneudorfer/Brive/model.py", line 79, in save_documents
self._save_single_document(backend, document)
File "/home/davidneudorfer/Brive/model.py", line 105, in _save_single_document
backend.save(self, document)
File "/home/davidneudorfer/Brive/backend.py", line 78, in save
f = open(path, 'w')
IOError: [Errno 2] No such file or directory: u'/home/davidneudorfer/google_docs_backup/2013-01-17T061021Z/coral.lopez/Lunchbox Monster High 4/7/12_1GyiuKFZeargO8KfzKS5H9V3PVbgTJufw2PwLaILzRVw.odt'
You could use the_str.replace('/', '_') to turn the path with '/'s in it into one with '_' in it.