【问题标题】:os.rename() not working in my python scriptos.rename() 在我的 python 脚本中不起作用
【发布时间】:2013-06-27 00:22:50
【问题描述】:

我正在编写一个脚本来将目录“./itunes and music/F14/”中的所有 .mp3、.m4a 和 .m4p 文件更改为另一个标题。我可以获取文件名,并且使用 hsaudiotag 我可以获取标题标签。但是,当我尝试将文件重命名为标题标签时,它给了我错误:

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

这是我的代码:

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()

所有的打印语句都只是为了调试,它们都工作正常。只是 os.rename() 函数不是。

【问题讨论】:

  • 文件名是否打印正确?
  • 是的,所有的文件名都打印好了。

标签: python operating-system rename windowserror


【解决方案1】:

指定文件路径,而不仅仅是文件名。

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()

【讨论】:

  • 这适用于所有 .mp3 文件,在 .m4a 和 .m4p 文件上我仍然得到:WindowsError: [错误 123] 文件名、目录名或卷标语法不正确
  • @user2528556,检查标题是否包含文件名的无效字符。 \ / : * ? < > |。替换此类字符。
猜你喜欢
  • 2018-11-03
  • 2019-09-28
  • 1970-01-01
  • 1970-01-01
  • 2017-05-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-31
相关资源
最近更新 更多