简体   繁体   中英

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. 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:

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.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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