os.lstat : proper way to do this

MRAB google at mrabarnett.plus.com
Fri Dec 12 18:43:07 EST 2008


m1k3b0 at gmail.com wrote:
> I'm converting from Perl to Python, so I'm learning the basics -
> please be gentle! :)
> 
> In Perl, I can lstat($file) whether $file exists or not:
> lstat($file);
> unless (-e _) {
>     print STDERR "$file: No such file or directory\n";
> }
> unless (-l _) {
>     print STDERR "$file: Not a symbolic link\n";
> }
> 
> The lstat() returns normally whether the file exists or not, and I
> check for existence with the "-e" conditional. Then I go on and check
> other modes.
> 
> In Python,if I os.lstat(file) and file doesn't exist, I get an error
> from within the module:
> OSError: [Errno 2] No such file or directory: '/etc/xxx'
> 
> I can check first with os.path.exists(file), but then I'm doing two
> stat() type calls which is inefficient (especially when we're talking
> thousands of files).
> 
> I want to be able to do something like this:
> mode = os.lstat(file)[ST_MODE]
> if not mode:
>     print >> sys.stderr, file, ": No such file or directory"
> if not S_ISLNK(mode):
>     print >> sys.stderr, file, ": Not a symbolic link"
> 
> Of course, this isn't valid. How can I do this efficiently without
> getting "no such file" error?
> 
Just catch the exception:

try:
     mode = os.lstat(file).st_mode # An alternative way.
     # If we get here then the file does exist.
     if not S_ISLNK(mode):
         print >> sys.stderr, file, ": Not a symbolic link"
except OSError, e:
     if e.errno == 2:
         # File doesn't exist.
         print >> sys.stderr, file, ": No such file or directory"
     else:
         # Failed for some other reason.


BTW, "file" happens to be the name of one of the build-ins, so try to 
use something else, eg. "file_path".



More information about the Python-list mailing list