Search code examples
python-3.xwindowspermissionsfile-permissionspermission-denied

win32 permission: Cannot delete file


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

Solution

  • 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