Testing for file type

A

Andrew Robert

Hi Everyone,

Is there a way to test if a file is binary or ascii within Python?

I'd prefer not to text against file extension.

Any help you can provide would be greatly appreciated.

Thanks,
Andy
 
D

Diez B. Roggisch

Andrew said:
Hi Everyone,

Is there a way to test if a file is binary or ascii within Python?


try:
open(filname).read().decode("ascii")
ascii = True
except UnicodeError:
ascii = False

Diez
 
L

Laurent Pointal

Andrew Robert a écrit :
Hi Everyone,

Is there a way to test if a file is binary or ascii within Python?

I'd prefer not to text against file extension.

Any help you can provide would be greatly appreciated.

May look at unix "file" command sources...


A+

L.Pointal.
 
B

BartlebyScrivener

In the Python Cookbook, 2ed, page 25, there's a script by Andrew Dalke
that uses the same heureistic criteria that Perl does and analyzes a
string and deems it binary if it contains any nulls or if more than 30%
of its characters have the high bit set or are strange control codes.

There's a follow on script that uses the same test on files.

rick
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,298
Messages
2,571,539
Members
48,274
Latest member
HowardKipp

Latest Threads

Top