In this tutorial, we will learn about how to fix the error “FileNotFoundError WinError 2 The system cannot find the file specified”. This error is very specific to Windows operating system. When you try to do any operation on a file which does not exist or Python is not able to locate, it will throw this error. We will look into more detail about the issue and the fix for the error in the upcoming section.
Why “FileNotFoundError WinError 2” Error Occurs?
The ‘FileNotFoundError WinError 2 The system cannot find the file specified’ error occurs in Python on Windows operating system when you attempt to access or manipulate a file that does not exist in the specified directory. This can happen when you try to open, read, write or perform any file-related operation on a file that has not been created or is not present in the specified location.
In this tutorial, we will reproduce the issue by using example code. We will create a Python code to rename the files in a specified path. Let us look at the below code.
Reproduce Error
import os def rename(directory): for name in os.listdir(directory): try: print("File before renaming: ",name) new_name = "Python" + name output = os.rename(name, new_name) print("File after renaming: ", new_name, "\n") except Exception as e: print(f"Error: {e}") path = r"C:\Users\linuxnasa\Desktop\Files" rename(path)
> python .\rename-file.py File before renaming: file1.txt Error: [WinError 2] The system cannot find the file specified: 'file1.txt' -> 'Pythonfile1.txt' File before renaming: file2.txt Error: [WinError 2] The system cannot find the file specified: 'file2.txt' -> 'Pythonfile2.txt'
FileNotFoundError WinError 2 The system cannot find the file specified
To fix the error, we will first switch to the specified directory using os.listdir() class. After switching to the specified directory, we can perform rename operation.
Resolve Error
import os def rename(directory): os.chdir(directory) for name in os.listdir(directory): try: print("File before renaming: ",name) new_name = "Python" + name output = os.rename(name, new_name) print("File after renaming: ", new_name, "\n") except Exception as e: print(f"Error: {e}") path = r"C:\Users\linuxnasa\Desktop\Files" rename(path)
> python .\rename-file.py File before renaming: file1.txt File after renaming: Pythonfile1.txt File before renaming: file2.txt File after renaming: Pythonfile2.txt
Summary
Reference Python os module