Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't resolve WindowsError: [Error 2] The system cannot find the file specified

Tags:

python

I'm trying to rename all the pictures in a directory. I need to add a couple of pre-pending zero's to the filename. I'm new to Python and I have written the following script.

import os

path = "c:\\tmp"
dirList = os.listdir(path)

for fname in dirList:
    fileName = os.path.splitext(fname)[0]
    fileName = "00" + fname
    os.rename(fname, fileName)
    #print(fileName)

The commented print line was just to verify I was on the right track. When I run this I get the following error and I am at a loss how to resolve it.

Traceback (most recent call last): File "C:\Python32\Code\add_zeros_to_std_imgs.py", line 15, in os.rename(fname, fileName) WindowsError: [Error 2] The system cannot find the file specified

Any help is greatly appreciated. Thnx.

like image 221
nyteshades Avatar asked Nov 16 '11 17:11

nyteshades


People also ask

How do I fix the system Cannot find the file specified?

Run CHKDSK Command to Fix "System Cannot Find File Specified" Device. Right-click the Start button, type cmd in the Search, and select Command Prompt (Admin). Type chkdsk x: /f /r (x represents your target drive) into the Command Prompt window and press Enter Wait while chkdsk tries to repair the corrupted file systems ...

How do I fix error 2 Python?

The Python "FileNotFoundError: [Errno 2] No such file or directory" occurs when we try to open a file that doesn't exist in the specified location. To solve the error, move the file to the directory where the Python script is located if using a local path, or use an absolute path.


1 Answers

You should pass the absolute path to os.rename. Right now your only passing the filename itself. It isn't looking in the correct place. Use os.path.join.

Try this:

import os

path = "c:\\tmp"
dirList = os.listdir(path)

for fname in dirList:
    fileName = os.path.splitext(fname)[0]
    fileName = "00" + fname
    os.rename(os.path.join(path, fname), os.path.join(path, fileName))
    #print(fileName)
like image 154
Casey Avatar answered Sep 21 '22 17:09

Casey