Python: A character that appears to be a space but

2019-07-20 18:50发布

This is in Python 3.4.

I'm writing my first program for myself and I'm stuck at a certain part. I'm trying to rename all of my audio files according to its metadata in python. However, when I try to rename the files, it doesn't finish renaming it sometimes. I think it is due to an invalid character. The problem is that I don't know what character it is. To me, it looks like a space but it isn't.

My code is here:

from tinytag import TinyTag
import os

print("Type in the file directory of the songs you would like to rename and organize:")
directory = input()
os.chdir(directory)
file_list = os.listdir(directory)

for item in file_list:
    tag = TinyTag.get(item)
    title = str(tag.title)
    artist = str(tag.artist)
    if artist[-1] == "\t" or artist[-1] == " ":
        print("Found it!")
    new_title = artist + "-" + title + ".mp3"
    #os.rename(item, new_title)
    print(new_title)

This is the list that it outputs: http://imgur.com/tfgBdMZ

It is supposed to output "Artist-Title.mp3" but sometimes it outputs "Artist -Title .mp3". When the space is there, python stops renaming it at that point. The first entry that does so is Arethra Franklin. It simply names the file Arethra Franklin rather than Arethra Franklin-Dr.Feelgood.mp3

Why does it do this? My main question is what is that space? I tried setting up a == boolean to see if it is a space (" ") but it isn't.

It ends the renaming by stopping once it hits that "space". It doesn't when it hits a normal space however.

1条回答
狗以群分
2楼-- · 2019-07-20 19:11

It's possible that the filename has some unicode in it. If all you are looking for is a file renamer, you could use str.encode and handle the errors by replacing them with a ? character. As an example:

# -*- coding: utf-8 -*-
funky_name = u"best_song_ever_пустынных.mp3"
print (funky_name)
print (funky_name.encode('ascii','replace'))

This gives:

best_song_ever_пустынных.mp3
best_song_ever_?????????.mp3

As mentioned in the comments, you can use ord to find out what the "offending space" really is.

查看更多
登录 后发表回答