Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

os.rename() not working in my python script

I'm writing a script to change all of the .mp3, .m4a and .m4p files in the directory './itunes and music/F14/' to another title. I'm able to get the filenames, and using hsaudiotag I can get the title tag. However, when I try to rename the file to the title tag it give me the error:

WindowsError: [Error 2] The system cannot find the file specified

Here's my code:

from hsaudiotag import auto
import os

def main():
    for filename in os.listdir('./itunes and music/F14/'):
        print(filename)
        os.rename(filename, filename[2:])
        myfile = auto.File('./itunes and music/F14/'+filename)
        print(myfile.title)
        if filename.endswith(".mp3"):
            print('3')
            os.rename(filename, myfile.title+".mp3")
        elif filename.endswith(".m4a"):
            print('4a')
            os.rename(filename, myfile.title+".m4a")
        elif filename.endswith(".m4p"):
            print('4p')
            os.rename(filename, myfile.title+".m4p")

main()

All of the print statements are just to debug, and they all are working properly. It's just the os.rename() function that isn't.

like image 493
Sonofblip Avatar asked Jun 07 '26 11:06

Sonofblip


1 Answers

Specify file path, not just filename.

from hsaudiotag import auto
import os

def main():
    d = './itunes and music/F14/'
    for filename in os.listdir(d):
        print(filename)
        filepath = os.path.join(d, filename)
        os.rename(filepath, filepath[2:])
        myfile = auto.File(filepath)
        print(myfile.title)
        if filename.endswith(".mp3"):
            print('3')
            os.rename(filepath, os.path.join(d, myfile.title+".mp3"))
        elif filename.endswith(".m4a"):
            print('4a')
            os.rename(filepath, os.path.join(d, myfile.title+".m4a"))
        elif filename.endswith(".m4p"):
            print('4p')
            os.rename(filepath, os.path.join(d, myfile.title+".m4p"))

main()
like image 200
falsetru Avatar answered Jun 10 '26 07:06

falsetru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!