Python Iterating through Directories and Renaming
<p>I am trying to iterate through a list of subdirectories and then opening the files within that subdirectory and renaming the files to lowercase. Here is my code:</p>

<pre><code>for root, subdirs, pics in os.walk(rootdir):
  for pic in pics:
    if pic.endswith('.jpg'):
        picpath = os.path.join(pic)
        #print pic
        print picpath
        #os.rename(pic, pic.replace(" ", "-").lower())
        os.rename(picpath, picpath.replace(" ", "-").lower())
</code></pre>

<p>I then get: </p>

<blockquote>
  <p><em>Traceback (most recent call last): File "imageresizing-renamefiles.py", line 19, in 
  os.rename(picpath, picpath.replace(" ", "-").lower()) OSError: [Errno
  2] No such file or directory</em></p>
</blockquote>

<p>My file structure is a root directory where the code runs from and within that folder are the following 
<code>folder1</code> with <code>Image1jpg</code> and <code>Image2jpg</code>, <code>folder2</code> with <code>Image3jpg</code> and <code>Image4jpg</code> and so on. I want to iterate through each to rename the files (not the folders) to lower case names.</p>

<p>Appreciate any help.</p>

<p>you have to append the directory name to your path or <code>os.rename</code> is unable to find the proper directory where to apply the rename.</p>

<p>That said, your conversion to lowercase complicates the task. lowercase must only be applied to the basename (that would work on Windows filesystem because case doesn't matter, but would fail on Linux if some directories of the path contain uppercase letters: fortunately, you cannot rename a whole dirtree with a single <code>rename</code> command)</p>

<p>And the match for <code>.jpg</code> extension should be done regardless of the casing, specially if you want to convert picture names to lowercase: extensions are likely to be in uppercase too (like all those DCIM cameras)</p>

<pre><code>for root, subdirs, pics in os.walk(rootdir):
  for pic in pics:
    if pic.lower().endswith('.jpg'):  # more powerful: fnmatch.fnmatch(pic,"*.jpg")
        os.rename(os.path.join(root,pic), os.path.join(root,pic.replace(" ", "-").lower()))
</code></pre>

python iteration rename