I'm preprocessing datas to apply deep learning on audio files. I have a directory of audio file (.wav) with differents length and my goal is to use 0 padding in order to have only 10 secondes files duration. I also want to move move files that are longer than 10 secondes in an other directory:
from pydub import AudioSegment
import os
import shutil
path_to_sound = r'my\path\to\sound'
path_to_export = r'my\path\to\export'
path_for_too_long = r'my\path\to\other_directory'
pad_ms= 10000
file_names=os.listdir(path_to_sound)
print(file_names) # ['30368.wav', '41348.wav', '42900.wav', '42901.wav', '42902.wav']
for name in file_names:
audio= AudioSegment.from_wav(os.path.join(path_to_sound, name))
if pad_ms > len(audio):
shutil.move(name,path_for_too_long )
else:
silence = AudioSegment.silent(duration=pad_ms-len(audio)+1)
padded = audio + silence
padded.export(os.path.join(path_to_export, name), format = 'wav')
When running this I got the following errors:
FileNotFoundError: [WinError 2] The specified file can not be found : '41348.wav' -> 'C:\\Users\\path_for_too_long\\41348.wav'
...
FileNotFoundError: [Errno 2] No such file or directory: '41348.wav'
I think the error is due to the way i'm using shutil.move()
shutil.move expects the full path, here you are providing the name which corresponds to the filename and not the file path.
You have to update the line:
shutil.move(name, path_for_too_long)
to:
shutil.move(os.path.join(path_to_sound, name), path_for_too_long)
Remark: if you are using Python 3.4+ you can use pathlib instead of os to handle paths. You can find 2 articles on this:
Why you should be using pathlib
No really, pathlib is great
before u delete,try to findout if is exist.
import os
path = ''
if os.path.exists(path):
func_to_delete()
Related
Hello as the title says i am writing a program which copys data from chrome. my current code is
#library imports
import sys
import shutil
import os
import subprocess
#search and find requried files.
os.path.expanduser('~user') #search for user path
#Making directory
newpath = r'F:\Evidence\Chromium'
newpath = r'F:\Evidence\Chrome'
#Copy chrome file
original = r'%LOCALAPPDATA%\Google\Chrome\User Data\Default\History'
target = r'F:\Evidence\Chrome'
shutil.copyfile(original, target)
i get a error on the line original = r'%LOCALAPPDATA%\Google\Chrome\User Data\Default\History'
i assume the script cannot read %LOCALAPPDATA%\ and needs the correct user path ?
what code do i need to input the user directory on a windows PC?
for example C:\Users\(Script to find out this part)\AppData\Local\Google\Chrome\User Data\Default
Scripv3.py", line 25, in <module>
shutil.copyfile(original, target)
File "C:\Users\darks\AppData\Local\Programs\Python\Python39\lib\shutil.py", line 261, in copyfile
with open(src, 'rb') as fsrc, open(dst, 'wb') as fdst:
FileNotFoundError: [Errno 2] No such file or directory: '%LOCALAPPDATA%\\Google\\Chrome\\User Data\\Default\\History'
Use the pathlib library.
from pathlib import Path
original = Path.home() / "Google/Chrome/User data/Default/History"
target = Path("F:/Evidence/Chrome")
shutil.copyfile(origina, target)
What you want to do is use os.path.expandvars() function on original variable:
os.path.expandvars(r'%LOCALAPPDATA%')
Will return:
C:\Users\USERNAME\AppData\Local
Where USERNAME is the name of the current user.
So, ensure the variables are expanded for this path:
original = os.path.expandvars(original)
before using it in shutil.copy(original, target)
Im trying to run my code with this but keep running into a file not found error.
files = [i for i in os.listdir('C:/Users/me/Desktop/python data')]
for filename in files:
data = pandas.read_excel(str(filename))
I've tried looking around but cant seem to understand.
Running print(os.getcwd()) does find the file in the folder but i still get the error message
You need to concatenate the path and the filename returned from os.listdir:
PATH = 'C:/Users/me/Desktop/python data'
files = [os.path.join(PATH, i) for i in os.listdir(PATH)]
for filename in files:
data = pandas.read_excel(str(filename))
Further recommendations:
You can use pathlib's .glob to get the full path without using os.path.join.
Also, if you use read_excel, please consider filtering by xls/xlsx files:
Code example:
import pathlib
path = pathlib.Path('C:/Users/me/Desktop/python data')
excel_filter = "*.xls*"
for filename in path.glob(excel_filter):
print(filename)
import os
for filename in os.listdir("C:/Users/Awesome/Music"):
if filename.endswith("lyrics.mp3"):
os.rename(filename,filename[0 : len(filename)-11]+".mp3")
The code above returns the error
File "c:/python/lyrics-pop.py", line 6, in <module>
os.rename(filename,filename[0 : len(filename)-11]+".mp3")
FileNotFoundError: [WinError 2] The system cannot find the file specified: '2 Chainz - Bigger Than You (feat Drake Quavo) lyrics.mp3' -> '2 Chainz - Bigger Than You (feat Drake Quavo).mp3'
"""
I have made sure that no other program is accessing the .mp3 files and removed the readonly attribute. What could be causing this?
Probably, the issue is that you are passing relative path to os.rename, add dir to file path, like this:
import os
dir = "C:/Users/Awesome/Music"
for filename in os.listdir(dir):
if filename.endswith("lyrics.mp3"):
os.rename(os.path.join(dir,filename),os.path.join(dir,filename[0 : len(filename)-11])+".mp3")
This is because python can not find the file from where this program is running, since full path is not given.
You can do it as follows:
import os
filedir = "C:/Users/Awesome/Music"
for filename in os.listdir(filedir):
if filename.endswith("lyrics.mp3"):
filepath = os.path.join(filedir, filename)
new_file = os.path.join(filedir, filename[0 : len(filename)-11]+".mp3")
os.rename(filepath, new_file)
As suggested in the comments, the problem seems to be the relative path of the files.
You can use glob, which will give you the full path, i.e.:
from glob import glob
from os import rename
for f in glob("C:/Users/Awesome/Music/*lyrics.mp3"):
rename(f, f[0 : len(f)-11]+".mp3")
I'm trying to rename an audio file but I keep getting OSError: [Errno 2] No such file or directory.
In my program, each user has a directory that holds the users files. I obtain the path for each user by doing the following:
current_user_path = os.path.join(current_app.config['UPLOAD_FOLDER'], user.username)
/Users/johnsmith/Documents/pythonprojects/project/files/john
Now I want to obtain the path for the existing file I want to rename:
current_file_path = os.path.join(current_user_path,form.currentTitle.data)
/Users/johnsmith/Documents/pythonprojects/project/files/john/File1
The path for the rename file will be:
new_file_path = os.path.join(current_user_path, form.newTitle.data)
/Users/johnsmith/Documents/pythonprojects/project/files/john/One
Now I'm just running the rename command:
os.rename(current_file_path, new_file_path)
you can use os.rename for rename single file.
to avoid
OSError: [Errno 2] No such file or directory.
check if file exist or not.
here is the working example:
import os
src = "D:/test/Untitled003.wav"
dst = "D:/test/Audio001.wav"
if os.path.isfile(src):
os.rename(src, dst)
If the OS says there's no such file or directory, that's the gospel truth. You're making a lot of assumptions about where the file is, constructing a path to it, and renaming it. It's a safe bet there's no such file as the one named by current_file_path, or no directory to new_file_path.
Try os.stat(current_file_path), and similarly double-check the new file path with os.stat(os.posixpath.dirname(new_file_path)). Once you've got them right, os.rename will work if you've got permissions.
Try changing the current working directory to the one you want to work with. This code below should give you a simple walk through of how you should go about it:
import os
print (os.getcwd())
os.chdir(r"D:\Python\Example")
print (os.getcwd())
print ("start")
def rename_files():
file_list= os.listdir(r"D:\Python\Example")
print(file_list)
for file_name in file_list:
os.rename(file_name,file_name.translate(None,"0123456789")) rename_files()
print("stop")
print (os.getcwd())
I already read some useful infos here about moving files with Python. But those are not working on my machine. I use eclipse to run python and the program should move files within windows.
I used os.rename, shutil.move, shutil.copy and so on....
Here is my simple code.
import os
import shutil
source = os.listdir("C:/test/")
dest_dkfrontend = "C:/test1/"
for files in source:
if files.startswith("Detail"):
print('Files found ' + files)
shutil.copy(files, dest_dkfrontend)
else:
print('File name not matching')
I receive an error like:
with open(src, 'rb') as fsrc:
IOError: [Errno 2] No such file or directory:
Could you please help to address this?
first you have to check if your destination directory exists or not.
and shutil.copy requires 1st parameter as source of file with file name and 2nd parameter as destination of file where to copy with new file name.
try this.
import os
import shutil
source = os.listdir("C:/test/")
dest_dkfrontend = "C:/test1/"
if not os.path.exists(dest_dkfrontend):
os.makedirs(dest_dkfrontend)
for files in source:
if files.startswith("Detail"):
print('Files found ' + files)
shutil.copy(source+files, dest_dkfrontend+files)
else:
print('File name not matching')