空格是字符吗python_Python:看起来像是空格但不是空格的字符。它是什么?

在Python中尝试根据元数据批量重命名音频文件时,遇到部分文件因包含特殊字符导致重命名失败的问题。作者发现这不是普通空格,而是可能的Unicode字符。解决方案建议使用str.encode处理错误,将不明字符替换为问号。通过ord函数可以找出问题字符。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

解决方案

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值