python - os.rename() 在我的 python 脚本中不起作用

标签 python operating-system rename windowserror

我正在编写一个脚本,将目录“./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() 函数不是。

最佳答案

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

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

关于python - os.rename() 在我的 python 脚本中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17378071/

相关文章:

python - 在 python 中使用 Tf-Idf 的搜索引擎

python - 如何获取多个未定义列不为空的 pandas DataFrame 的第一个索引?

c++ - 从单独的线程访问单独的文件,这是否有效?

opengl - 是否可以在 OpenGL 中一次保留所有状态?

html - 下载的网站模板在 Mac OS X 上似乎充满了可执行文件,我应该担心吗?

使用 dplyr 重命名未命名变量

python - 修复多列条件的值

python - 中文字符插入问题

git diff 重命名/move 和修改的文件但跳过重命名/move 和相同的文件

php - 通过集群和移动进行高效的文件更新