os.chdir doesn't accept variables sometimes

Donn Cave donn at u.washington.edu
Fri Jun 2 19:52:41 CEST 2006


In article <1149267516.348440.60290 at u72g2000cwu.googlegroups.com>,
 "dannycolligan at gmail.com" <dannycolligan at gmail.com> wrote:

> #!/usr/bin/python
> 
> from os import *
> 
> chdir("/home/chainlynx/Desktop/Music")
> for artist in listdir(getcwd()):
>         print "===ARTIST: "+artist
>         chdir(artist)
>         for album in listdir(getcwd()):
>                 print "---ALBUM: "+album
>                 print "CWD: " + getcwd()
>                 chdir(album)                       ######ERROR ON THIS
> LINE
>                 for string in listdir(album):
...

> Traceback (most recent call last):
>   File "/home/chainlynx/workspace/PyTest/src/pypack/__init__.py", line
> 12, in ?
>     for string in listdir(album):
> OSError: [Errno 2] No such file or directory: 'Album1'

To start with, note that your traceback implicates the listdir()
on line 12, not the chdir() before it.  This listdir() uses the
same parameter as that preceding chdir(), that appears to be your
problem.

One of your problems, anyway.  You're doing a lot of downwards
chdirs, but no upwards, which is going to limit the extent of
your directory traversal.

The "from os import *" is a terrible idea, where did you get that?
"os" has a lot of identifiers in it that tend to collide with other
namespaces.  "open" is a classic example.  Don't do that, with "os"
or generally any module.

As a more general direction, it would be a good idea to look
into standard library functions, e.g., os.path.walk

> P.S. Bonus points: is there any way to bash shell script this on the
> command line instead (recursively)?

Depends on what you want it to do, but maybe something like

 find . -name \*.mp3 -exec $HOME/bin/cvt .mp4 {} \;

where cvt would be something like
   #!/bin/sh
   case $1:$2 in
   .mp4:*.mp3)  mp3_to_mp4 $2 ${2%.mp3}.mp4 ;;
   ...

You'd have to think about it.

   Donn Cave, donn at u.washington.edu



More information about the Python-list mailing list