determine file type

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Mark Gibson

    #1

    determine file type

    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
  • James Stroud

    #2
    Re: determine file type

    Mark Gibson wrote:[color=blue]
    > 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[/color]

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


    James



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


    Comment

    • Mark Gibson

      #3
      Re: determine file type

      [color=blue]
      >
      >
      > import os
      > def test_file(filen ame, maxread=1024):
      > if os.path.isdir(f ilename):
      > return 'directory'
      > afile = open(filename) # open as text
      > for achar in afile.read(maxr ead):
      > if ord(achar) > 127:
      > return 'binary'
      > return 'text'
      >
      >[/color]

      Pefect, thanks!

      Comment

      • Steven D'Aprano

        #4
        Re: determine file type

        On Sun, 26 Mar 2006 19:52:32 -0700, Mark Gibson wrote:
        [color=blue]
        >[color=green]
        >>
        >>
        >> import os
        >> def test_file(filen ame, maxread=1024):
        >> if os.path.isdir(f ilename):
        >> return 'directory'
        >> afile = open(filename) # open as text
        >> for achar in afile.read(maxr ead):
        >> if ord(achar) > 127:
        >> return 'binary'
        >> return 'text'
        >>
        >>[/color]
        >
        > Pefect, thanks![/color]

        Not only is it not perfect, as given it isn't even correct.
        [color=blue][color=green][color=darkred]
        >>> open("lots_of_n ulls.bin", "w").write( "\0" * 1024)
        >>> test_file("lots _of_nulls.bin")[/color][/color][/color]
        'text'

        However, with a more careful algorithm for deciding what's text and what's
        not, the general approach is fine.


        --
        Steven.

        Comment

        Working...