简体   繁体   English

在 Python 中使用 os.rename() 重命名文件时出错

[英]Error while renaming files with os.rename() in Python

import os

for filename in os.listdir("C:/Users/Awesome/Music"):
    if filename.endswith("lyrics.mp3"):
        os.rename(filename,filename[0 : len(filename)-11]+".mp3")

The code above returns the error上面的代码返回错误

File "c:/python/lyrics-pop.py", line 6, in <module>
    os.rename(filename,filename[0 : len(filename)-11]+".mp3")
FileNotFoundError: [WinError 2] The system cannot find the file specified: '2 Chainz - Bigger Than You (feat Drake  Quavo) lyrics.mp3' -> '2 Chainz - Bigger Than You (feat Drake  Quavo).mp3'

""" """

I have made sure that no other program is accessing the.mp3 files and removed the readonly attribute.我确保没有其他程序正在访问 .mp3 文件并删除了 readonly 属性。 What could be causing this?这可能是什么原因造成的?

Probably, the issue is that you are passing relative path to os.rename, add dir to file path, like this:可能问题是您将相对路径传递给 os.rename,将 dir 添加到文件路径,如下所示:

import os
dir = "C:/Users/Awesome/Music"
for filename in os.listdir(dir):
    if filename.endswith("lyrics.mp3"):
        os.rename(os.path.join(dir,filename),os.path.join(dir,filename[0 : len(filename)-11])+".mp3")

This is because python can not find the file from where this program is running, since full path is not given.这是因为 python 找不到运行该程序的文件,因为没有给出完整路径。

You can do it as follows:你可以这样做:

import os
filedir = "C:/Users/Awesome/Music"
for filename in os.listdir(filedir):
    if filename.endswith("lyrics.mp3"):
        filepath = os.path.join(filedir, filename)
        new_file = os.path.join(filedir, filename[0 : len(filename)-11]+".mp3")
        os.rename(filepath, new_file)

As suggested in the comments, the problem seems to be the relative path of the files.正如评论中所建议的,问题似乎是文件的相对路径。
You can use glob , which will give you the full path, ie:您可以使用glob ,它将为您提供完整路径,即:

from glob import glob
from os import rename

for f in glob("C:/Users/Awesome/Music/*lyrics.mp3"):
    rename(f, f[0 : len(f)-11]+".mp3")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM