Renaming files in Python: No such file or directory
<p>If I try to rename files in a directory, for some reason I get an error.
I think the problem may be that I have not inserted the directory in the proper format ?</p>

<p>Additional info:
python 2 &amp;
linux machine</p>

<blockquote>
  <p>OSError: [Errno 2] No such file or directory</p>
</blockquote>

<p>Though it prints the directories content just fine. What am I doing wrong?</p>

<pre><code>import os

for i in os.listdir("/home/fanna/Videos/strange"):
    #print str(i)
    os.rename(i, i[:-17])
</code></pre>

<p>Suppose there is a file <code>/home/fanna/Videos/strange/name_of_some_video_file.avi</code>, and you're running the script from <code>/home/fanna</code>.</p>

<p><code>i</code> is <code>name_of_some_video_file.avi</code> (the name of the file, not including the full path to it). So when you run</p>

<pre><code>os.rename(i, i[:-17])
</code></pre>

<p>you're saying</p>

<pre><code>os.rename("name_of_some_video_file.avi", "name_of_some_video_file.avi"[:-17])
</code></pre>

<p>Python has no idea that these files came from <code>/home/fanna/Videos/strange</code>. It resolves them against the currrent working directory, so it's looking for <code>/home/fanna/name_of_some_video_file.avi</code>.</p>

python