Solution: windowserror: [error 2]

There is a problem when renaming a file by using the rename() function of python, which prompts windows error: [error 2]. The initial 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)

Later, after repeated attempts, the problem was solved~

Before rename, you need to use the chdir() function to enter the path of the target file to tell the python compiler where the file to be renamed is, and then you can modify it;

Python is not a terrible terminator. In fact, she is very young. She can’t find the file herself. We need to tell her where to find the path in detail and patiently 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 simple. You can rename any file by modifying filepre and FileNew.

Read More: