0

i have some pieces of mp3 that's recovered from my damaged hard disk. then i found some of the mp3s had been damaged, but some were ok. so, i'm using the following code to filter those damaged mp3s. `

import os
from pydub import AudioSegment
fname= 'C:\\Users\\Desktop\\1.mp3'
try:
    sound1 = AudioSegment.from_file(fname)
except:
    print(fname)
    base, extension = os.path.splitext(fname)
    p, name = os.path.split(base)
    os.rename(fname, p + '\\' + name + '[damaged]' + extension)

`

but in the os.rename part, it prints error:PermissionError: [WinError 32] it suggests that the file has been occupied by python programe. how to solute the problem? thanks

user8641707
  • 199
  • 2
  • 9

2 Answers2

0

use this library

from os.path import join

And this for rename

os.rename(join(p,fname), join(p,name)+'[damaged]' + extension)
Jay Shankar Gupta
  • 5,918
  • 1
  • 10
  • 27
  • problem is that the mp3 file has been opened by 'AudioSegment.from_file(fname)' because when `try` captures errors(because the mp3 file is a damaged one), it won't close the mp3 file.so in the `except` part, `os.rename` cannot rename a file that's been kept opened by another programe. because of this, you even cannot rename the file mannually. – user8641707 Mar 29 '18 at 03:26
0

this one worked.

import os
from pydub import AudioSegment
fname= 'C:\\Users\\Desktop\\1.mp3'
try:
    #sound1 = AudioSegment.from_file(fname)
    with open(fname, "rb") as wav_file:
         sound1 = AudioSegment.from_file(wav_file)except:

except:
    print(fname)
    base, extension = os.path.splitext(fname)
    p, name = os.path.split(base)
    os.rename(fname, p + '\\' + name + '[damaged]' + extension)
user8641707
  • 199
  • 2
  • 9