[Tutor] Move all files to top-level directory

Sander Sweers sander.sweers at gmail.com
Mon Apr 12 19:12:32 CEST 2010

On 12 April 2010 18:28, Dotan Cohen <dotancohen at gmail.com> wrote:
> However, it fails like this:
> $ ./moveUp.py
> Traceback (most recent call last):
>  File "./moveUp.py", line 8, in <module>
>    os.rename(f, currentDir)
> TypeError: coercing to Unicode: need string or buffer, tuple found

os.rename needs the oldname and the new name of the file. os.walk
returns a tuple with 3 values and it errors out.

Also os.getcwd returns the working dir so if you run it in the wrong
folder you will end up with a mess. In idle on my windows machine at
work this is what is gives me.

>>> os.getcwd()

So it is better to give the program the path you want it to look in
rather then relying on os.getcwd().

os.walk returns you a tuple with the following values:
(the root folder, the folders in the root, the files in the root folder).

You can use tuple unpacking to split each one in separate values for
your loop. Like:

for root, folder, files in os.walk('your path):
   #do stuff

It might be wise to only have this module print what it would do
instead of doing the actual move/rename so you can work out the bugs
first before it destroys your data.

Hope this helps.

More information about the Tutor mailing list