There was a problem renaming the file with the Python rename () function, prompting Windowserror: [Error 2] error, the original code is as follows:
def renamefile (filename):
filepre = "d:\\filedemo\\python\\pt.py"
os.rename (filepre, filename)
print Os.listdir (filepre)
if __name__ = = ' __main__ ':
filenew = "d:\\filedemo\\python\\test.py"
renamefile ( FileNew)
Then after repeated attempts to solve the problem ~
Before rename, use the ChDir () function to enter the path to the destination file, telling the Python compiler where to rename the file before it can be modified;
Python is not a terrible terminator, she is very young, she can not find the file, we need to be detailed and patient to tell her where to find the ~ path is obtained through the Os.path.dirname () function:
Import OS
from NT import chdir
def renamef (Prename, newName):
chdir (Os.path.dirname (prename))
Os.rename (Prename, newName)
if __name__ = = ' __main__ ':
filepre = "D:\FileDemo\Python\PT.py" filenew
= " D:\FileDemo\Python\Test.txt "
renamef (Filepre, FileNew)
The code is very concise, and you can rename any file by modifying filepre,filenew.