determine file type

James Stroud jstroud at ucla.edu
Sun Mar 26 19:55:43 EST 2006


Mark Gibson wrote:
> Is there an equivalent to the unix 'file' command?
> 
> [mark tmp]$ file min.txt
> min.txt: ASCII text
> [mark tmp]$ file trunk
> trunk: directory
> [mark tmp]$ file compliance.tgz
> compliance.tgz: gzip compressed data, from Unix
> 
> What I really want to do is determine if a file is 1) a directory, 2) a 
> text file 3) a binary file.
> 
> Is there a way to do this?
> 
> Mark

import os
def test_file(filename, maxread=1024):
   if os.path.isdir(filename):
     return 'directory'
   afile = open(filename) # open as text
   for achar in afile.read(maxread):
     if ord(achar) > 127:
       return 'binary'
   return 'text'


James



-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/



More information about the Python-list mailing list