Python - 无法重命名文件名中包含特殊字符的文件 [英] Python - Unable to rename a file with special characters in the file name

查看:2739
本文介绍了Python - 无法重命名文件名中包含特殊字符的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堆mp3文件,在第0个索引中有某个特殊字符。所以文件名称看起来像这样▶单独晚上 - 收音机编辑 - 以上&超越.mp3



我想要能够解决这个问题。在python中,当我列出文件时,它显示如下:

 '? Alone Tonight  -  Radio Edit  - 以上&除了.mp3'

我想要做的是使用<$但是,当我这样做:


$

b $ b

  newfilename = filename [2:len(filename)] 
os.rename(filename,newfilename)

我获得


WindowsError:[错误123]目录名或卷
标签语法不正确


那么我的选项是什么?它看起来像windows不会识别特殊字符。

解决方案

您可以使用文件的unicode名称更好的运气。
要获取unicode名称,请将unicode路径传递到 os.listdir

  for os.listdir(u'/ path / to / files'):
如果filename.startswith(u'\\\▶'):
os.rename ,filename [2:])

请注意,使用unicode可能不足以指定文件名(你可能必须规范化unicode),因为多个unicode代码点序列可以有相同的外观和意义。 (请参阅 unicode等效性,以及Ned Batchelder的关于主题的博文)。


I have a bunch of mp3 files that somehow have a special character in the 0th index. So the file name looks like this - ▶ Alone Tonight - Radio Edit - Above & Beyond .mp3

I want to be able to fix this. In python, when I list the file, it shows up like this:

'? Alone Tonight - Radio Edit - Above & Beyond .mp3'

All I want to do is to rename this file with the substring defined by [2:len(filename)]

However, when I do this:

newfilename = filename[2:len(filename)]
os.rename(filename,newfilename)

I get

WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect

So what are my options? It looks like windows wont' recognize the special character. I am able to manually edit it, but not programmatically.

解决方案

You may have better luck using the unicode name for the file. To obtain the unicode name, pass a unicode path to os.listdir.

for filename in os.listdir(u'/path/to/files'):
    if filename.startswith(u'\u25b6'):
        os.rename(filename, filename[2:])

Note that using unicode may not always be quite enough to specify the filename (you may have to normalize the unicode), since more than one unicode code point sequence can have the same appearance and meaning. (See unicode equivalence, and Ned Batchelder's blog post on the subject).

这篇关于Python - 无法重命名文件名中包含特殊字符的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆