简体   繁体   中英

Python eyed3 UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 17: ordinal not in range(128)

Trying to rename all files in a directory using eye3d 0.7.8-final

#! /usr/bin/env python
import os, sys, unicodedata, eyed3

def parse(sourcefile):
    audiofile = eyed3.load(sourcefile)
    if audiofile.tag.artist != audiofile.tag.artist:
        if audiofile.tag.title != audiofile.tag.title:
            temp = u"{0} - {1}.mp3".format(audiofile.tag.artist, audiofile.tag.title)
            os.rename(sourcefile, temp)

def main():
    for filelist in os.listdir('.'):
        if filelist.endswith('.mp3'):
           print u"Processing: {0}".format(filelist)
               parse(filelist)

if __name__ == "__main__":
    os.system('clear')
    main()

I though that adding the u"" to temp and print would resolves these but I am still getting

Traceback (most recent call last):
File "./test.py", line 19, in <module>
main()
File "./test.py", line 14, in main
print u"Processing: {0}".format(filelist)

UnicodeDecodeError: 'ascii' codec can't decode byte 0xcc in position 14: ordinal not in range(128)

I have also attempted this

reload(sys)
sys.setdefaultencoding('utf8')

Which resulted in the following

Traceback (most recent call last):
File "./test.py", line 21, in <module>
main()
File "./test.py", line 14, in main
print u"Processing: {0}".format(filelist)

UnicodeEncodeError: 'ascii' codec can't encode character u'\u0308' in position 26: ordinal not in range(128)

Per @DevShark I set the following but the same error is displayed

temp = temp.encode('ascii','ignore')

Traceback (most recent call last):
File "./test.py", line 22, in <module>
main()
File "./test.py", line 15, in main
print u"Processing: {0}".format(filelist)

UnicodeEncodeError: 'ascii' codec can't encode character u'\u0308' in position 26: ordinal not in range(128)

So it seems the files renamed correctly but there is still a problem with the

filelist = filelist.encode('ascii','ignore')
print u"Processing: {0}".format(filelist)

I would suggest to not use unicode to name files, use ascii instead. Depending on your operating system, it can cause bad behaviour.

You can just add the following line before you rename your file:

temp = temp.encode('ascii', 'ignore')

It will just skip the unicode characters in your file names, and will fix your code.

If you want to keep unicode names and not ascii, I would suggest you make sure you understand well the concepts before. It's one of these things that can lead to a lot of pain down the road if done without a clear understanding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM