[Tutor] checking if data files are good, readable, and exist
Tim Golden
mail at timgolden.me.uk
Tue Jul 22 18:05:56 CEST 2008
Bryan Fodness wrote:
> I would like to check to see if the data files are good, readable, and
> exist. I have checked to see if they exist, but their is a possibility
> that the data file might be binary, and I would like to have a sys.exit
> for that as well.
You're going to be asked a lot of questions along the lines
of "What do you mean by binary?". I'm going to assume you
mean: has things other than ordinary letters, numbers
and punctuation in it. In today's internationalised and
Unicoded world that's a highly dodgy assumption, but I'm
going to go with it.
To compound the crudeness of my approach, I'm going to
assume that anything > 126 is "binary" (thus dodging
the more complicated issue of the 0-31 control chars).
<code>
def is_binary (filename):
return any (ord (c) > 126 for c in open (filename).read ())
print is_binary ("file1.txt")
</code>
Obviously, if you know any of the files is going to be
massive, you'll want to do something a bit smarter than
this.
TJG
More information about the Tutor
mailing list