0

I know that this is a question that's been asked before. I have tried all the possible solutions provided in those queries on stackoverflow but none of them has worked out.

So i have this python code in which I am trying to delete files,audio files(of wav format) specifically. I don't know why windows won't let me delete files.

The error occurs here----> os.remove(j) PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'æ1.wav'

This has been pricking me for a while now. Because I don't see this file being open or used anywhere else apart from the one in which I am using currently.

import soundfile as sf
import os

phon=['a','æ', 'ʌ','ɔ','ɑʊ', 'ɑɪ', 'b', 'ʧ', 'd', 'ð', 'ɛ', 'ɜɹ', 'eɪ', 'f', 'ɡ', 'h', 'i', 'ɪː', 'ʤ', 'k','l','m','n', 'ŋ', 'oʊ',
       'p','ɹ', 's', 'ʃ', 't', 'θ', 'ʊ', 'u', 'v', 'w', 'j', 'z','ʒ','ɔɪ' ]

count=0
for i in phon:
    path='C:\\Users\\enviz\\pron_dictionaries-master\\all_words\\all_phonemes\\'+i
    os.makedirs(path , exist_ok=True)
    os.chdir(path)
    x=len(os.listdir(os.getcwd())) 
    files = os.listdir(path)


    for j in files:
        f = sf.SoundFile(j)
        duration = (len(f) / f.samplerate)
        size_of_audio = (os.path.getsize(j))/1024


        #get rid of files less than 3KB
        if(size_of_audio<=3 or duration<0.15):

                os.remove(j) #the error is on this line
envi z
  • 677
  • 7
  • 13

1 Answers1

3

I think you have the file open. You need to close it as stated in the docs:

If a file is opened, it is kept open for as long as the SoundFile object exists. The file closes when the object is garbage collected, but you should use the soundfile.SoundFile.close() method or the context manager to close the file explicitly

jcragun
  • 2,060
  • 10
  • 8
  • thank you . I never thought that it was because of SoundFile. I thought it was mostly because of the OS that I was using. – envi z Mar 29 '19 at 05:36
  • @enviz, it is a Windows issue. POSIX systems don't implement a cooperative data-access model in the access check at time of open. There is no way around it other than closing the file reference that's blocking shared read/execute, write/append, or delete/rename access. Very rarely does an open share delete/rename access in Windows. – Eryk Sun Mar 30 '19 at 02:02
  • @eryksun does this happen especially in jupyter notebooks often? – envi z Mar 30 '19 at 04:51
  • @enviz, almost always deleting or renaming will be problem if a file is left open, since sharing delete access is so uncommon. And it's not always as obvious as `sf.SoundFile(j)`. – Eryk Sun Mar 30 '19 at 06:47
  • @eryksun i tried to use contextlib to open the wav files like this: with contextlib.closing(wave.open(path+i+'\\'+j,'r')) as f: #do something with the file f.close() #runs without any error – envi z Apr 01 '19 at 17:16