Determine if a file path is a file or a directory

From CodeCodex

Revision as of 23:00, 24 December 2010 by 211.2.129.92 (Talk)

Implementations

Java

    File dir = new File("directoryName");
    
    boolean isDir = dir.isDirectory();
    if (isDir) {
        // dir is a directory
    } else {
        // dir is a file
    }

Perl

print "it's a directory\n" if -d $path;
print "it's a file\n" if -f $path;
print "it's a symlink\n" if -l $path;
print "it's a pipe\n" if -p $path;
print "it's a socket\n" if -S $path;

Python

Note: A Path can be more than a directory or a (normal) file!

import os

if os.path.isdir(path):
    print "it's a directory"
elif os.path.isfile(path):
    print "it's a normal file"
else:
    print "it's a special file (socket, FIFO, device file)"

Ruby

filename = '/work'
type = File.ftype(filename)
case type
when "file"
  puts "#{filename} is a normal file"
when "directory"
  puts "#{filename} is a directory"
else
  puts "#{filename} is a special file (#{type})"
end