Re: [Tutor] reading binary files

2009-02-03 Thread eShopping

Bob

I am trying to read UNFORMATTED files.  The files also occur as 
formatted files and the format string I provided is the string used 
to write the formatted version.  I can read the formatted version 
OK.  I (naively) assumed that the same format string was used for 
both files, the only differences being whether the FORTRAN WRITE 
statement indicated unformatted or formatted.


Best regards

Alun Griffiths

At 21:41 03/02/2009, bob gailer wrote:
First question: are you trying to work with the file written 
UNFORMATTED? If so read on.


If you are working with a file formatted (1X, 1X, A8, 1X, 1X, I6, 
1X, 1X, A1) then we have a completely different issue to deal with. 
Do not read on, instead let us know.


eShopping wrote:


Data format:

TIME  1  F  0.0
DISTANCE 10  F  0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0

F=float, D=double, L=logical, S=string etc


The first part of the file should contain a string (eg "TIME"),
an integer (1) and another string (eg "F") so I tried using

import struct
in_file = open(file_name+".dat","rb")
data = in_file.read()
items = struct.unpack('sds', data)

Now I get the error

error: unpack requires a string argument of length 17

which has left me completely baffled!


Did you open the file with mode 'b'? If not change that.

You are passing the entire file to unpack when you should be 
giving it only the first "line". That's why is is complaining 
about the length. We need to figure out the lengths of the lines.


Consider the first "line"

TIME  1  F  0.0

There were (I assume)  4 FORTRAN variables written here: character 
integer character float. Without knowing the lengths of the 
character variables we are at a loss as to what the struct format 
should be. Do you know their lengths? Is the last float or double?


Try this: print data[:40] You should see something like:

TIME...\x01\x00\x00\x00...F...\x00\x00\x00\x00...DISTANCE...\n\x00\x00\x00

where ... means 0 or more intervening stuff. It might be that the 
\x01 and the \n are in other places, as we also have to deal with 
"byte order" issues.


Please do this and report back your results. And also the FORTRAN 
variable types if you have access to them.


Apologies if this is getting a bit messy but the files are at a 
remote location and I forgot to bring copies home.  I don't have 
access to the original FORTRAN program so I tried to emulate the 
reading the data using the Python script below.  AFAIK the FORTRAN 
format line for the header is  (1X, 1X, A8, 1X, 1X, I6, 1X, 1X, 
A1).  If the data following is a float it is written using n(1X, 
F6.2) where n is the number of records picked up from the preceding header.


# test program to read binary data

import struct

# create dummy data

data = []
for i in range(0,10):
data.append(float(i))

# write data to binary file

b_file = open("test.bin","wb")

b_file.write("  %8s  %6d  %1s\n" % ("DISTANCE", len(data), "F"))
for x in data:
b_file.write(" %6.2f" % x)


You are still confusing text vs binary. The above writes text 
regardless of the file mode. If the FORTRAN file was written 
UNFORMATTED then you are NOT emulating that with the above program. 
The character data is read back in just fine, since there is no 
translation involved in the writing nor in the reading. The integer 
len(data) is being written as its text (character) representation 
(translating binary to text) but being read back in without 
translation. Also all the floating point data is going out as text.


The file looks like (where b = blank) (how it would look in notepad):

bbDISTANCEbb10bFbbb0.00bbb1.00bbb2.00 If you analyze this with 2s8s2si2s1s
you will see 2s matches bb, 8s matches DISTANCE, 2s matches bb, i 
matches . (\x40\x40\x40\x40). The i tells unpack to shove those 
4 bytes unaltered into a Python integer, resulting in 538976288. You 
can verify that:


>>> struct.unpack('i', '')
(538976288,)

Please either assure me you understand or are prepared for a more in 
depth tutorial.

b_file.close()

# read back data from file

c_file = open("test.bin","rb")

data = c_file.read()
start, stop = 0, struct.calcsize("2s8s2si2s1s")

items = struct.unpack("2s8s2si2s1s",data[start:stop])
print items
print data[:40]

I'm pretty sure that when I tried this at the other PC there were a 
bunch of \x00\x00 characters in the file but they don't appear in 
NotePad  ... anyway, I thought the Python above would unpack the 
data but items appears as


('  ', 'DISTANCE', '  ', 538976288, '10', ' ')

which seems to be contain an extra item (538976288)

Alun Griffiths



--
Bob Gailer
Chapel Hill NC
919-636-4239


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Can you help me with subprocess module ?.

2009-02-03 Thread Larry Riedel
> I have a problem with the subprocess module. In fact I wish
> that when I run the command with subprocess I can retrieve the
> data immediately without waiting for the end of the command.
>
> import subprocess, os, sys
> # Commande FFmpeg
> com_1 = 'ffmpeg -i /home/user/path/in.avi -s 160x120 -ac 1
>   -ar 22050 -qmin 3 -qmax 3 -y /home/user/path/out.avi'
> p = [subprocess.Popen(com_1, stderr=subprocess.STDOUT,
> stdout=subprocess.PIPE, shell=True).communicate()[0]]

The "communicate" method waits for the process to exit.
Maybe look farther down the page for "Replacing os.popen"
http://docs.python.org/library/subprocess.html


Larry
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Sort of database & "family tree" question

2009-02-03 Thread ALAN GAULD
> > And I assume you are reading these into a Person class and
> > storing these classes in a persons dictionary? 


> Can you explain this a little more for me please?


Sure. 
(I didn't notice this on gmane so apologies if others already answered)

> The current way of reading the data is this:
> 
> parser = ConfigParser.ConfigParser()
> parser.read(personFile)
> 
> def get_info(person)
>infoDic = {}
>infoDic['first']  = parser.get(person, 'firstName')
>infoDic['last']   = parser.get(person, 'lastName')
>infoDic['father']   = parser.get(person, 'father')
>infoDic['mother'] = parser.get(person, 'mother')
>return infoDic

TYhis is almost the same but you are using a dict. A sligtly more readable 
version is to define a class Person:

class Person:
 def __init__(self, parser):
 self.first  = parser.get(person, 'firstName')
 self.last   = parser.get(person, 'lastName')
 self.father   = parser.get(person, 'father')
 self.mother = parser.get(person, 'mother')

Now you can create your person records with:

parser = ConfigParser.ConfifgParser()
parser.read(personFile)

people = {}
# some kind of loop here?
# for record in parser...
  p = Person(parser)
  people[p.first,p.last] = p

Now you will have a dictionary full of persons and you can access them 
by the first,last tuple of their name.

BUT how is father/mother stored? Is it a first/last tuple or some ID number? 
If an ID you need to add that to your Person definition and use it as the 
people key.

Does that help?

Alan G.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] struct question

2009-02-03 Thread Alan Gauld


"bob gailer"  wrote 


>>> struct.calcsize('s')
1
>>> struct.calcsize('d')
8
>>> struct.calcsize('sd')
16

Why? Should not that be 9?


Numbers always start on word boundaries.


struct.calcsize('ds')

9

Alan G.


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] re weird bool

2009-02-03 Thread Alan Gauld


"prasad rao"  wrote


2==True

False

It is an unexpected result to me.
I thought any value other than 0 is True.


Any value of non zero is treated as True in a boolean context.
But aq test of equality with a boolean value is not a boolean context.
For equiality you have to compare like with like, and you do that
by taking the boolean value of the number using bool()

So:

if 2: print 'True'
else: print 'False'

will print true
but

if 2 == True: print 'True'
else: print 'False'

will print False.
The two tests are not identical.

HTH,

--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Can you help me with subprocess module ?.

2009-02-03 Thread PyProg PyProg
Hello everyone,

I have a problem with the subprocess module. In fact I wish that when
I run the command with subprocess I can retrieve the data immediately
without waiting for the end of the command. I tried this way but
ordering must end so that I can recover the data:

import subprocess, os, sys

# Commande FFmpeg
com_1 = 'ffmpeg -i /home/user/path/in.avi -s 160x120 -ac 1 -ar 22050
-qmin 3 -qmax 3 -y /home/user/path/out.avi'

p = [subprocess.Popen(com_1, stderr=subprocess.STDOUT,
stdout=subprocess.PIPE, shell=True).communicate()[0]]

for toto in p:
>if '\r' in toto:
>tampon = str(toto).split(' ')
># ..., 'time=151.6', ...
>for vb in tampon:
>if 'time' in vb:
>tempsEcoule = vb[5:]
>print u'Temps écoulé', tempsEcoule

My version of Python:

Python 2.5.2 (r252:60911, Jul 31 2008, 17:31:22)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2

Can you help me?.

Excuse me in advance for my bad English.

a +

-- 
http://ekd.tuxfamily.org
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Parsing suggestion? (CUE file)

2009-02-03 Thread Kent Johnson
On Tue, Feb 3, 2009 at 5:17 PM, Terry Carroll  wrote:
> On Tue, 3 Feb 2009, Kent Johnson wrote:
>
>> I would look at pyparsing for that, and make sure cuetools won't do
>> what you want.
>
> csv seems to be working well for me, and it's a standard piece of Python,
> which I prefer to use.  I don't think I'm twisting it out of its intended
> useh: despite its name, it's really about splitting up uniform delimited
> input lines.  The ability to use other delimeters and to trim the
> left-padding seems consistent with my use of it.

I think your use of the csv module is fine. What I really meant to say
was more like, I would have looked to pyparsing to solve the same
problem, and if you want a parser that parses the file into meaningful
records, then it might still be worth a look. If we talk about it
enough, maybe Paul McGuire will contribute the parser :-)

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Parsing suggestion? (CUE file)

2009-02-03 Thread Terry Carroll
On Tue, 3 Feb 2009, Kent Johnson wrote:

> Ah, I see. I imagined something more ambitious, that treated the lines
> as fields. 

I find that the more ambitious my projects become, the less likely I am to 
complete them!  With two toddlers, on a good day, I get 30 to 60 minutes 
of discretionary time, some of which I can do some coding!

> You are using csv to do kind of a smart split() function.

That's an excellent summary.

> I would look at pyparsing for that, and make sure cuetools won't do
> what you want.

csv seems to be working well for me, and it's a standard piece of Python,
which I prefer to use.  I don't think I'm twisting it out of its intended
useh: despite its name, it's really about splitting up uniform delimited
input lines.  The ability to use other delimeters and to trim the
left-padding seems consistent with my use of it.

The time it took between thinking of using CSV and getting it to actually 
work was probably a lot less time than I would have spend downloading and 
installing pyparsing, and figuring out how it worked.

Thanks for the cuetools tip.  I hadn't heard of it before.  I spent some 
time looking for tools related to Audacity and CUE files, and couldn't 
find much (apart from one forum posting pointing out that Audacity didn't 
support CUE files, but it would be pretty easy to convert a CUE file to an 
Audacity label file).

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Parsing suggestion? (CUE file)

2009-02-03 Thread Kent Johnson
On Tue, Feb 3, 2009 at 3:26 PM, Terry Carroll  wrote:
> On Tue, 3 Feb 2009, Kent Johnson wrote:
>
>> On Tue, Feb 3, 2009 at 2:55 PM, Terry Carroll  wrote:
>>
>> > The silver cloud to my temporary Internet outage was that I was able to
>> > solve my problem, in the process discovering that the csv module can parse
>> > a CUE file[1] quite nicely if you set up an appropriate csv.Dialect class.
>> >
>> > [1] http://en.wikipedia.org/wiki/Cue_file
>>
>> What is the dialect? That sounds like a useful trick.
>
> This seems to be working for me, at least with the sample CUE files I've
> tested with so far:
>
> ###
> import csv
>
> class cue(csv.Dialect):
>"""Describe the usual properties of CUE files."""
>delimiter = ' '
>quotechar = '"'
>doublequote = True
>skipinitialspace = True
>lineterminator = '\r\n'
>quoting = csv.QUOTE_MINIMAL
> csv.register_dialect("cue", cue)
>
> f = open("test.cue", "r")
> reader = csv.reader(f,dialect="cue")
> for row in reader:
>print row
> ###
>
> The dialect is the same as the standard excel dialect, which I cribbed out
> of csv.py, except for delimiter and skipinitialspace.

Ah, I see. I imagined something more ambitious, that treated the lines
as fields. You are using csv to do kind of a smart split() function.

> My project is to write a program to convert a CUE file into a list of
> labels that can be imported into Audacity; and perhaps a file of ID3 info
> that can be imported into MP3 tagging software.  If I had to parse the
> blank-separated fields of quoted text that included blanks, I don't know
> how long this would have taken me.

I would look at pyparsing for that, and make sure cuetools won't do
what you want.

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] reading binary files

2009-02-03 Thread bob gailer
First question: are you trying to work with the file written 
UNFORMATTED? If so read on.


If you are working with a file formatted (1X, 1X, A8, 1X, 1X, I6, 1X, 
1X, A1) then we have a completely different issue to deal with. Do not 
read on, instead let us know.


eShopping wrote:


Data format:

TIME  1  F  0.0
DISTANCE 10  F  0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0

F=float, D=double, L=logical, S=string etc


The first part of the file should contain a string (eg "TIME"),
an integer (1) and another string (eg "F") so I tried using

import struct
in_file = open(file_name+".dat","rb")
data = in_file.read()
items = struct.unpack('sds', data)

Now I get the error

error: unpack requires a string argument of length 17

which has left me completely baffled!



Did you open the file with mode 'b'? If not change that.

You are passing the entire file to unpack when you should be giving 
it only the first "line". That's why is is complaining about the 
length. We need to figure out the lengths of the lines.


Consider the first "line"

TIME  1  F  0.0

There were (I assume)  4 FORTRAN variables written here: character 
integer character float. Without knowing the lengths of the character 
variables we are at a loss as to what the struct format should be. Do 
you know their lengths? Is the last float or double?


Try this: print data[:40] You should see something like:

TIME...\x01\x00\x00\x00...F...\x00\x00\x00\x00...DISTANCE...\n\x00\x00\x00 



where ... means 0 or more intervening stuff. It might be that the 
\x01 and the \n are in other places, as we also have to deal with 
"byte order" issues.


Please do this and report back your results. And also the FORTRAN 
variable types if you have access to them.


Apologies if this is getting a bit messy but the files are at a remote 
location and I forgot to bring copies home.  I don't have access to 
the original FORTRAN program so I tried to emulate the reading the 
data using the Python script below.  AFAIK the FORTRAN format line for 
the header is  (1X, 1X, A8, 1X, 1X, I6, 1X, 1X, A1).  If the data 
following is a float it is written using n(1X, F6.2) where n is the 
number of records picked up from the preceding header.


# test program to read binary data

import struct

# create dummy data

data = []
for i in range(0,10):
data.append(float(i))

# write data to binary file

b_file = open("test.bin","wb")

b_file.write("  %8s  %6d  %1s\n" % ("DISTANCE", len(data), "F"))
for x in data:
b_file.write(" %6.2f" % x)


You are still confusing text vs binary. The above writes text regardless 
of the file mode. If the FORTRAN file was written UNFORMATTED then you 
are NOT emulating that with the above program. The character data is 
read back in just fine, since there is no translation involved in the 
writing nor in the reading. The integer len(data) is being written as 
its text (character) representation (translating binary to text) but 
being read back in without translation. Also all the floating point data 
is going out as text.


The file looks like (where b = blank) (how it would look in notepad):

bbDISTANCEbb10bFbbb0.00bbb1.00bbb2.00 If you analyze this with 
2s8s2si2s1s
you will see 2s matches bb, 8s matches DISTANCE, 2s matches bb, i 
matches . (\x40\x40\x40\x40). The i tells unpack to shove those 4 
bytes unaltered into a Python integer, resulting in 538976288. You can 
verify that:


>>> struct.unpack('i', '')
(538976288,)

Please either assure me you understand or are prepared for a more in 
depth tutorial.

b_file.close()

# read back data from file

c_file = open("test.bin","rb")

data = c_file.read()
start, stop = 0, struct.calcsize("2s8s2si2s1s")

items = struct.unpack("2s8s2si2s1s",data[start:stop])
print items
print data[:40]

I'm pretty sure that when I tried this at the other PC there were a 
bunch of \x00\x00 characters in the file but they don't appear in 
NotePad  ... anyway, I thought the Python above would unpack the data 
but items appears as


('  ', 'DISTANCE', '  ', 538976288, '10', ' ')

which seems to be contain an extra item (538976288)

Alun Griffiths




--
Bob Gailer
Chapel Hill NC
919-636-4239
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] reading binary files

2009-02-03 Thread eShopping

Bob
At 19:52 03/02/2009, you wrote:

etrade.griffi...@dsl.pipex.com wrote:

Data format:

TIME  1  F  0.0
DISTANCE 10  F  0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0

F=float, D=double, L=logical, S=string etc


The first part of the file should contain a string (eg "TIME"),
an integer (1) and another string (eg "F") so I tried using

import struct
in_file = open(file_name+".dat","rb")
data = in_file.read()
items = struct.unpack('sds', data)

Now I get the error

error: unpack requires a string argument of length 17

which has left me completely baffled!



Did you open the file with mode 'b'? If not change that.

You are passing the entire file to unpack when you should be giving 
it only the first "line". That's why is is complaining about the 
length. We need to figure out the lengths of the lines.


Consider the first "line"

TIME  1  F  0.0

There were (I assume)  4 FORTRAN variables written here: character 
integer character float. Without knowing the lengths of the 
character variables we are at a loss as to what the struct format 
should be. Do you know their lengths? Is the last float or double?


Try this: print data[:40] You should see something like:

TIME...\x01\x00\x00\x00...F...\x00\x00\x00\x00...DISTANCE...\n\x00\x00\x00

where ... means 0 or more intervening stuff. It might be that the 
\x01 and the \n are in other places, as we also have to deal with 
"byte order" issues.


Please do this and report back your results. And also the FORTRAN 
variable types if you have access to them.


Apologies if this is getting a bit messy but the files are at a 
remote location and I forgot to bring copies home.  I don't have 
access to the original FORTRAN program so I tried to emulate the 
reading the data using the Python script below.  AFAIK the FORTRAN 
format line for the header is  (1X, 1X, A8, 1X, 1X, I6, 1X, 1X, 
A1).  If the data following is a float it is written using n(1X, 
F6.2) where n is the number of records picked up from the preceding header.


# test program to read binary data

import struct

# create dummy data

data = []
for i in range(0,10):
data.append(float(i))

# write data to binary file

b_file = open("test.bin","wb")

b_file.write("  %8s  %6d  %1s\n" % ("DISTANCE", len(data), "F"))
for x in data:
b_file.write(" %6.2f" % x)

b_file.close()

# read back data from file

c_file = open("test.bin","rb")

data = c_file.read()
start, stop = 0, struct.calcsize("2s8s2si2s1s")

items = struct.unpack("2s8s2si2s1s",data[start:stop])
print items
print data[:40]

I'm pretty sure that when I tried this at the other PC there were a 
bunch of \x00\x00 characters in the file but they don't appear in 
NotePad  ... anyway, I thought the Python above would unpack the data 
but items appears as


('  ', 'DISTANCE', '  ', 538976288, '10', ' ')

which seems to be contain an extra item (538976288)

Alun Griffiths





___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Parsing suggestion? (CUE file)

2009-02-03 Thread Terry Carroll
On Tue, 3 Feb 2009, Kent Johnson wrote:

> On Tue, Feb 3, 2009 at 2:55 PM, Terry Carroll  wrote:
> 
> > The silver cloud to my temporary Internet outage was that I was able to
> > solve my problem, in the process discovering that the csv module can parse
> > a CUE file[1] quite nicely if you set up an appropriate csv.Dialect class.
> >
> > [1] http://en.wikipedia.org/wiki/Cue_file
> 
> What is the dialect? That sounds like a useful trick.

This seems to be working for me, at least with the sample CUE files I've 
tested with so far:

###
import csv

class cue(csv.Dialect):
"""Describe the usual properties of CUE files."""
delimiter = ' '
quotechar = '"'
doublequote = True
skipinitialspace = True
lineterminator = '\r\n'
quoting = csv.QUOTE_MINIMAL
csv.register_dialect("cue", cue)

f = open("test.cue", "r")
reader = csv.reader(f,dialect="cue")
for row in reader:
print row
###

The dialect is the same as the standard excel dialect, which I cribbed out
of csv.py, except for delimiter and skipinitialspace.

My project is to write a program to convert a CUE file into a list of 
labels that can be imported into Audacity; and perhaps a file of ID3 info 
that can be imported into MP3 tagging software.  If I had to parse the 
blank-separated fields of quoted text that included blanks, I don't know 
how long this would have taken me.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Parsing suggestion? (CUE file)

2009-02-03 Thread Kent Johnson
On Tue, Feb 3, 2009 at 2:55 PM, Terry Carroll  wrote:

> The silver cloud to my temporary Internet outage was that I was able to
> solve my problem, in the process discovering that the csv module can parse
> a CUE file[1] quite nicely if you set up an appropriate csv.Dialect class.
>
> "Comma Separated Values"; it's not just for commas any more.
>
> [1] http://en.wikipedia.org/wiki/Cue_file

What is the dialect? That sounds like a useful trick.

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] struct question

2009-02-03 Thread Kent Johnson
On Tue, Feb 3, 2009 at 2:03 PM, Marc Tompkins  wrote:

> More results to chew on:
>
 struct.calcsize('s')
> 1
 struct.calcsize('d')
> 8
 struct.calcsize('sd')
> 16
 struct.calcsize('ds')
> 9
 struct.calcsize('dss')
> 10
 struct.calcsize('dss')
> 14
 struct.calcsize('dsd')
> 24
>
> I believe it's a matter of alignment:

Right. The struct module uses native alignment unless you tell it
otherwise. Native alignment is the same as if you defined a C struct
for the given items. In this case the double must start on an 8-byte
boundary.

If you don't want padding, use 'standard' alignment by specifying one
of the modifier prefixes, e.g. '!s!d'

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Parsing suggestion? (CUE file)

2009-02-03 Thread Terry Carroll
On Tue, 3 Feb 2009, Terry Carroll wrote:

> I am parsing certai

Sorry about that.  I was composing this message last night when my 
Internet connection went down.  When I logged on this morning, I had a 
partial message.  I meant to cancel but unfortunately, in pine, the SEND 
key (CTRL-X) is adjacent to the CANCEL key (CTRL-C), and I hit the wrong 
one.

The silver cloud to my temporary Internet outage was that I was able to 
solve my problem, in the process discovering that the csv module can parse 
a CUE file[1] quite nicely if you set up an appropriate csv.Dialect class.

"Comma Separated Values"; it's not just for commas any more.

[1] http://en.wikipedia.org/wiki/Cue_file

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] reading binary files

2009-02-03 Thread bob gailer

etrade.griffi...@dsl.pipex.com wrote:

Data format:

TIME  1  F  0.0
DISTANCE 10  F  0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0

F=float, D=double, L=logical, S=string etc

  
The first part of the file should contain a string (eg "TIME"),

an integer (1) and another string (eg "F") so I tried using

import struct
in_file = open(file_name+".dat","rb")
data = in_file.read()
items = struct.unpack('sds', data)

Now I get the error

error: unpack requires a string argument of length 17

which has left me completely baffled! 

  


Did you open the file with mode 'b'? If not change that.

You are passing the entire file to unpack when you should be giving it 
only the first "line". That's why is is complaining about the length. We 
need to figure out the lengths of the lines.


Consider the first "line"

TIME  1  F  0.0

There were (I assume)  4 FORTRAN variables written here: character 
integer character float. Without knowing the lengths of the character 
variables we are at a loss as to what the struct format should be. Do 
you know their lengths? Is the last float or double?


Try this: print data[:40] You should see something like:

TIME...\x01\x00\x00\x00...F...\x00\x00\x00\x00...DISTANCE...\n\x00\x00\x00

where ... means 0 or more intervening stuff. It might be that the \x01 
and the \n are in other places, as we also have to deal with "byte 
order" issues.


Please do this and report back your results. And also the FORTRAN 
variable types if you have access to them.



--
Bob Gailer
Chapel Hill NC
919-636-4239
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] struct question

2009-02-03 Thread Marc Tompkins
On Tue, Feb 3, 2009 at 11:05 AM, bob gailer  wrote:

> I have submitted this as a bug. Same behavior with c instead of s.
>

I don't think it's a bug.  Each double requires 8 bytes; that 8 bytes needs
to start at an 8-byte boundary.  If your struct starts with a 1-byte object,
then some empty padding bytes need to be inserted.  It's like loading the
dishwasher.

--
www.fsrtechnologies.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] struct question

2009-02-03 Thread bob gailer

W W wrote:



On Tue, Feb 3, 2009 at 6:25 PM, bob gailer > wrote:


>>> struct.calcsize('s')
1
>>> struct.calcsize('d')
8
>>> struct.calcsize('sd')
16

Why? Should not that be 9?


>>> struct.calcsize('ds')
9

at least on the current box I'm running. It also gave me this:

>>> struct.calcsize('sd')
12

so I must confess suspicion...


I have submitted this as a bug. Same behavior with c instead of s.



--
Bob Gailer
Chapel Hill NC
919-636-4239
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] struct question

2009-02-03 Thread Marc Tompkins
On Tue, Feb 3, 2009 at 10:29 AM, W W  wrote:

>
>
> On Tue, Feb 3, 2009 at 6:25 PM, bob gailer  wrote:
>
>> >>> struct.calcsize('s')
>> 1
>> >>> struct.calcsize('d')
>> 8
>> >>> struct.calcsize('sd')
>> 16
>>
>> Why? Should not that be 9?
>>
>
> >>> struct.calcsize('ds')
> 9
>
> at least on the current box I'm running. It also gave me this:
>
> >>> struct.calcsize('sd')
> 12
>
> so I must confess suspicion...
>
> HTH though,
> Wayne
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
More results to chew on:

>>> struct.calcsize('s')
1
>>> struct.calcsize('d')
8
>>> struct.calcsize('sd')
16
>>> struct.calcsize('ds')
9
>>> struct.calcsize('dss')
10
>>> struct.calcsize('dss')
14
>>> struct.calcsize('dsd')
24

I believe it's a matter of alignment:

> Native size and alignment are determined using the C compiler's 
> sizeofexpression. This is always combined with native byte order.
>
> Standard size and alignment are as follows: no alignment is required for
> any type (so you have to use pad bytes); short is 2 bytes; int and longare 4 
> bytes;
> long long (__int64 on Windows) is 8 bytes; float and double are 32-bit and
> 64-bit IEEE floating point numbers, respectively. _Bool is 1 byte.
>

-- 
www.fsrtechnologies.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Parsing suggestion? (CUE file)

2009-02-03 Thread Terry Carroll
I am parsing certai

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] struct question

2009-02-03 Thread W W
On Tue, Feb 3, 2009 at 6:25 PM, bob gailer  wrote:

> >>> struct.calcsize('s')
> 1
> >>> struct.calcsize('d')
> 8
> >>> struct.calcsize('sd')
> 16
>
> Why? Should not that be 9?
>

>>> struct.calcsize('ds')
9

at least on the current box I'm running. It also gave me this:

>>> struct.calcsize('sd')
12

so I must confess suspicion...

HTH though,
Wayne
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] struct question

2009-02-03 Thread bob gailer

>>> struct.calcsize('s')
1
>>> struct.calcsize('d')
8
>>> struct.calcsize('sd')
16

Why? Should not that be 9?

--
Bob Gailer
Chapel Hill NC
919-636-4239

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Sort of database & "family tree" question

2009-02-03 Thread Timo

Alan Gauld schreef:

Timo  wrote


So my entry's look like this (more or less ;)):
[person1]
firstName = foo
lastName = bar
father = person2
mother = person3


And I assume you are reading these into a Person class and
storing these classes in a persons dictionary? Then to access
a father becomes:

x = 'Person5'
print Persons[x].father.firstName



Can you explain this a little more for me please?


The current way of reading the data is this:

parser = ConfigParser.ConfigParser()
parser.read(personFile)

def get_info(person)
   infoDic = {}
   infoDic['first']  = parser.get(person, 'firstName')
   infoDic['last']   = parser.get(person, 'lastName')
   infoDic['father']   = parser.get(person, 'father')
   infoDic['mother'] = parser.get(person, 'mother')
   return infoDic


But maybe it can be done better.

Timo



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] regex: not start with FOO

2009-02-03 Thread Kent Johnson
On Tue, Feb 3, 2009 at 11:12 AM, Bernard Rankin  wrote:

> In [3]: re.findall('^(?!FOO)in', 'in in in')
> Out[3]: ['in']
>
> In [4]: re.findall('(?!^FOO)in', 'in in in')
> Out[4]: ['in', 'in', 'in']
>
> In [5]: re.findall('(?!FOO)in', 'in in in')
> Out[5]: ['in', 'in', 'in']
>
> In [6]: re.findall('(?!FOO$)in', 'in in in')
> Out[6]: ['in', 'in', 'in']
>
> In [7]: re.findall('(?!^FOO$)in', 'in in in')
> Out[7]: ['in', 'in', 'in']
>
>
> What is the effective difference between numbers 4 thru 7?
>
> That is, what effect does a string position anchor have within the sub 
> expression?

6 & 7 are meaningless; you can never have an end-of-line ($) followed by text.

> Hmm...
>
> In [30]: re.findall('(?!FOO)in', 'in FOOin in')
> Out[30]: ['in', 'in', 'in']

OK. (?!...) is a look *ahead* assertion - it requires that the current
match not be followed by the given expression. It seems that this is
meaningless at the start of a regex, since there is no current match.
In other words, '(?!FOO)in' matches 'in FOOin in' at position 6
because starting at position 6 there is no FOO.

You should use a look-behind assertion, or just put the ^ outside the assertion.

In [2]: re.findall('(?!FOO)in', 'in FOOin in')
Out[2]: ['in', 'in', 'in']

In [3]: re.findall('(?http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] regex: not start with FOO

2009-02-03 Thread Bernard Rankin



> > I'd like to match any line that does not start with FOO.  (Using just a 
> > reg-ex 
> rule)
> >
> > 1) What is the effective difference between:
> >
> > (?!^FOO).*
> >
> > ^(?!FOO).*
> 
> One difference is that the first will match starting anywhere in a
> string, while the second will match only at the start. For this exact
> example I don't think it matters but if you replace .* with something
> else you can see a difference. For example:
> In [52]: re.findall('(?!^FOO) in', 'in in in')
> Out[52]: [' in', ' in']
> 
> In [53]: re.findall('^(?!FOO) in', 'in in in')
> Out[53]: []
> 
> I think I would use the second form, it seems to more directly express
> what you mean.
> 

Thank you... that clarifies things greatly.

Now, to change the example slightly:

In [3]: re.findall('^(?!FOO)in', 'in in in')
Out[3]: ['in']

In [4]: re.findall('(?!^FOO)in', 'in in in')
Out[4]: ['in', 'in', 'in']

In [5]: re.findall('(?!FOO)in', 'in in in')
Out[5]: ['in', 'in', 'in']

In [6]: re.findall('(?!FOO$)in', 'in in in')
Out[6]: ['in', 'in', 'in']

In [7]: re.findall('(?!^FOO$)in', 'in in in')
Out[7]: ['in', 'in', 'in']


What is the effective difference between numbers 4 thru 7?

That is, what effect does a string position anchor have within the sub 
expression?

Thank you,
:)


  

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] regex: not start with FOO

2009-02-03 Thread Bernard Rankin



> > I'd like to match any line that does not start with FOO.  (Using just a 
> > reg-ex 
> rule)
> >
> > 1) What is the effective difference between:
> >
> > (?!^FOO).*
> >
> > ^(?!FOO).*
> 
> One difference is that the first will match starting anywhere in a
> string, while the second will match only at the start. For this exact
> example I don't think it matters but if you replace .* with something
> else you can see a difference. For example:
> In [52]: re.findall('(?!^FOO) in', 'in in in')
> Out[52]: [' in', ' in']
> 
> In [53]: re.findall('^(?!FOO) in', 'in in in')
> Out[53]: []
> 
> I think I would use the second form, it seems to more directly express
> what you mean.
> 

Hmm...

In [30]: re.findall('(?!FOO)in', 'in FOOin in')
Out[30]: ['in', 'in', 'in']


OK, now I am confused... . why am I getting 3 results?



  

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] transforming an integer to a list of integers

2009-02-03 Thread Kent Johnson
On Tue, Feb 3, 2009 at 10:17 AM, H.G. le Roy  wrote:

> One step for my solution should be transforming this big integer to a list
> of integers. I did:
>
> import math
>
> bignr = 12345
> bignrs =[]
>

The suggestions with strings are fine, but you can simplify your
approach as well:

> for i in xrange(math.ceil(math.log10(bignr)):

No need for the complicated range expression, just use
while bignr > 0:

>   rem = bignr % 10
>   bignrs.append(rem)
>   bignr /= 10

Using the divmod() function you can compute rem and the new value for
bignr in one operation:
bignr, rem = divmod(bignr, 10)

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] transforming an integer to a list of integers

2009-02-03 Thread Andre Engels
On Tue, Feb 3, 2009 at 4:24 PM, Andre Engels  wrote:
> On Tue, Feb 3, 2009 at 4:17 PM, H.G. le Roy  wrote:
>> Hi,
>>
>> recently I learned about Project Euler (http://projecteuler.net/) and now
>> I'm trying to work me through. At the moment I'm thinking about
>> http://projecteuler.net/index.php?section=problems&id=8
>>
>> One step for my solution should be transforming this big integer to a list
>> of integers. I did:
>>
>> import math
>>
>> bignr = 12345
>> bignrs =[]
>>
>> for i in xrange(math.ceil(math.log10(bignr)):
>>   rem = bignr % 10
>>   bignrs.append(rem)
>>   bignr /= 10
>>
>> However this "feels" a bit complicated, Do you know a better (more simple,
>> nice etc.) way to do this?
>
> One way could be to represent the number as a string; a string can be
> treated as a list, so you get what you want quite quickly that way:
>
> bignr = 12345
> bignrs =[]
>
> for char in str(bignr):
>bignrs.append(int(char))

Or as a one-liner:

bignr = 12345
bignrs =[int(char) for char in str(bignr)]


-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] transforming an integer to a list of integers

2009-02-03 Thread Andre Engels
On Tue, Feb 3, 2009 at 4:17 PM, H.G. le Roy  wrote:
> Hi,
>
> recently I learned about Project Euler (http://projecteuler.net/) and now
> I'm trying to work me through. At the moment I'm thinking about
> http://projecteuler.net/index.php?section=problems&id=8
>
> One step for my solution should be transforming this big integer to a list
> of integers. I did:
>
> import math
>
> bignr = 12345
> bignrs =[]
>
> for i in xrange(math.ceil(math.log10(bignr)):
>   rem = bignr % 10
>   bignrs.append(rem)
>   bignr /= 10
>
> However this "feels" a bit complicated, Do you know a better (more simple,
> nice etc.) way to do this?

One way could be to represent the number as a string; a string can be
treated as a list, so you get what you want quite quickly that way:

bignr = 12345
bignrs =[]

for char in str(bignr):
bignrs.append(int(char))




-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] transforming an integer to a list of integers

2009-02-03 Thread Ken Oliver
Not an expert here, but I think I would first change it to a big string of 1000 chars and then pick off the chars one at a time and do int().-Original Message-
From: "H.G. le Roy" 
Sent: Feb 3, 2009 10:17 AM
To: tutor@python.org
Subject: [Tutor] transforming an integer to a list of integers

Hi,recently I learned about Project Euler (http://projecteuler.net/) and now I'm trying to work me through. At the moment I'm thinking about http://projecteuler.net/index.php?section=problems&id=8
One step for my solution should be transforming this big integer to a list of integers. I did:import mathbignr = 12345bignrs =[]for i in xrange(math.ceil(math.log10(bignr)):  rem = bignr % 10
  bignrs.append(rem)  bignr /= 10However this "feels" a bit complicated, Do you know a better (more simple, nice etc.) way to do this?Thanks 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] transforming an integer to a list of integers

2009-02-03 Thread H.G. le Roy
Hi,

recently I learned about Project Euler (http://projecteuler.net/) and now
I'm trying to work me through. At the moment I'm thinking about
http://projecteuler.net/index.php?section=problems&id=8

One step for my solution should be transforming this big integer to a list
of integers. I did:

import math

bignr = 12345
bignrs =[]

for i in xrange(math.ceil(math.log10(bignr)):
  rem = bignr % 10
  bignrs.append(rem)
  bignr /= 10

However this "feels" a bit complicated, Do you know a better (more simple,
nice etc.) way to do this?

Thanks
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] re division problem

2009-02-03 Thread Andre Engels
On Tue, Feb 3, 2009 at 2:46 PM, prasad rao  wrote:
> hi
>>Right now you skip by x+((len(v))/columns)
>>which will be different for each row.
> How is it possible. len(v)=98.A constant.
> Is it not.
> Does len(v) changes with each iteration?

No, but x does.


-- 
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] re division problem

2009-02-03 Thread prasad rao
hi>Right now you skip by x+((len(v))/columns)
>which will be different for each row.
How is it possible. len(v)=98.A constant.
Is it not.
Does len(v) changes with each iteration?

Prasad
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] re division problem

2009-02-03 Thread Kent Johnson
On Tue, Feb 3, 2009 at 8:24 AM, prasad rao  wrote:
>> I wrote a function named vertical to print string .printable characters
>> and
> .>> ASCII values in a table.
>>> 1)It is swallowing some characters.
>>> 2)It output some characters  2 or 3 times.
>>> 3)It prints one column more than what I asked for.
>
>>> def vertical(columns):
>>> import string
>>> v=string.printable
>>> v=v.replace('\n','')
>>> v=v.replace('\t','')
>
>>What is len(v) here? What is len(v)/columns?
> There are 100 characters  in the string(string.printable)
> I deleted '\n\t'. So 98/say 4==24.5 So if there is a fraction
> I have to round it off to 1. So 24.5 should be rounded off
> to 25..But is there a better way to print it  in given number
> of columns

Right. One way to do integer division that rounds up is like this:
skip = (len(v) + columns - 1) / columns

>
>>> for x in range((len(v))/columns):
>>> for y in range(x,len(v),x+((len(v))/columns)):
>
>>The third argument to range() is the step size. Do you want to use a
>>different step size for each row?
> No. How can I ensure that every value is an integer  but without missing
> in retrieving an element in the string.

Not sure what you mean by that. How many elements do you need to skip
to get to the next column? Right now you skip by x+((len(v))/columns)
which will be different for each row.

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] re weird bool

2009-02-03 Thread prasad rao
helloyes.you are right.
>>> 2==True
False

It is an unexpected result to me.
I thought any value other than 0 is True.
And the solution provided by you(bool(a/1))
is useful to me.

Thank you
Prasad
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] re division problem

2009-02-03 Thread prasad rao
> I wrote a function named vertical to print string .printable characters
and
.>> ASCII values in a table.
>> 1)It is swallowing some characters.
>> 2)It output some characters  2 or 3 times.
>> 3)It prints one column more than what I asked for.

>> def vertical(columns):
>> import string
>> v=string.printable
>> v=v.replace('\n','')
>> v=v.replace('\t','')

>What is len(v) here? What is len(v)/columns?
There are 100 characters  in the string(string.printable)
I deleted '\n\t'. So 98/say 4==24.5 So if there is a fraction
I have to round it off to 1. So 24.5 should be rounded off
to 25..But is there a better way to print it  in given number
of columns

>> for x in range((len(v))/columns):
>> for y in range(x,len(v),x+((len(v))/columns)):

>The third argument to range() is the step size. Do you want to use a
>different step size for each row?
No. How can I ensure that every value is an integer  but without missing
in retrieving an element in the string.

Prasad
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Division problems

2009-02-03 Thread Kent Johnson
On Tue, Feb 3, 2009 at 3:42 AM, prasad rao  wrote:
> Hello
> I wrote a function named vertical to print string .printable characters and
> ASCII values in a table.
> 1)It is swallowing some characters.
> 2)It output some characters  2 or 3 times.
> 3)It prints one column more than what I asked for.

> def vertical(columns):
> import string
> v=string.printable
> v=v.replace('\n','')
> v=v.replace('\t','')

What is len(v) here? What is len(v)/columns?

> for x in range((len(v))/columns):
> for y in range(x,len(v),x+((len(v))/columns)):

The third argument to range() is the step size. Do you want to use a
different step size for each row?

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] regex: not start with FOO

2009-02-03 Thread Kent Johnson
On Mon, Feb 2, 2009 at 5:46 PM, Bernard Rankin  wrote:
> Hello,
>
>
> I'd like to match any line that does not start with FOO.  (Using just a 
> reg-ex rule)
>
> 1) What is the effective difference between:
>
> (?!^FOO).*
>
> ^(?!FOO).*

One difference is that the first will match starting anywhere in a
string, while the second will match only at the start. For this exact
example I don't think it matters but if you replace .* with something
else you can see a difference. For example:
In [52]: re.findall('(?!^FOO) in', 'in in in')
Out[52]: [' in', ' in']

In [53]: re.findall('^(?!FOO) in', 'in in in')
Out[53]: []

I think I would use the second form, it seems to more directly express
what you mean.

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] weird bool

2009-02-03 Thread Andre Engels
On Tue, Feb 3, 2009 at 11:40 AM, prasad rao  wrote:
> hi
 a=2.1
 a%1==True
> False
 a%1==False
> False
 b=3.8
 b%1==True
> False
 b%1==False
> False
> If it gives correct bool, it could be put to good use.

== gives a high degree of equality. In your idea, it would not be a
kind of equality at all, because you would have:

>>> 1 == True
True
>>> 2 == True
True
>>> 1 == 2
False

It would also be confusion as to when '==' would mean logical equality
and when real equality:

 1 == ((0 == 0) or not (0==0))
True
 1 == ((0 + 0) * (0 + 0))
False
 True == 1
???

Finally, it is rarely necessary:
>>> a=2.1
>>> bool(a%1)==True
True

That's a few characters more, but to me that's more than compensated
by the gains in clarity and consistency (== is an equivalence
relationship, at least unless you have redefined it for your own class
in a less practical way)

--
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] weird bool

2009-02-03 Thread prasad rao
hi
>>> a=2.1
>>> a%1==True
False
>>> a%1==False
False
>>> b=3.8
>>> b%1==True
False
>>> b%1==False
False

If it gives correct bool, it could be put to good use.
Prasad
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] reading binary files

2009-02-03 Thread etrade . griffiths
Sorry, still having problems 


> >  I am trying to read data from a file that has format
> > item_name  num_items  item_type  items 
> > 
> > eg
> > 
> > TIME  1  0.0
> > DISTANCE 10  0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0
> 
> Where is the item_type?
Ooops, the data format should look like this:

TIME  1  F  0.0
DISTANCE 10  F  0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0

F=float, D=double, L=logical, S=string etc

> 
> > I can read this if the data are in ASCII format using
> > 
> >in_file = open("my_file.dat","r")
> >data1 = in_file.read()
> >tokens = data1.split()
> 
> It might be easier to process line by line using readline 
> or readlines rather than read but otherwise, ok so far...
> 
> > and then stepping through the resulting list but the data 
> > also appear in the same format in a binary file.  
> 
> When you say a binary file do you mean an ASCII file 
> encoded into binary using some standard algorithm?
> Or do you mean the data is binary so that, for example, 
> the number 1 would appear as 4 bytes? If so do you 
> know how strings (the name) are delimited? Also 
> how many could be present - is length a single or 
> multiple bytes? and are the reors fixed length or 
> variable? If variable what is the field/record separator?

Sorry, no idea what the difference is.  All I know is that the data
were written by a FORTRAN program using the UNFORMATTED argument
in the WRITE statement and that if they had been written FORMATTED
then we would get  afile that looks something like the example above

> 
> You may need to load the file into a hex editor of debugger 
> to determine the answers...
> 
> Having done that the struct module will allow you to read 
> the data.
> 
> You can see a basic example of using struct in my 
> tutorial topic about handling files.

The first part of the file should contain a string (eg "TIME"),
an integer (1) and another string (eg "F") so I tried using

import struct
in_file = open(file_name+".dat","rb")
data = in_file.read()
items = struct.unpack('sds', data)

Now I get the error

error: unpack requires a string argument of length 17

which has left me completely baffled! 

> 
> 
> --
> 
> Message: 4
> Date: Mon, 02 Feb 2009 14:53:59 -0700
> From: Bernd Prager 
> Subject: [Tutor] question about mpmath product expression
> To: tutor@python.org
> Message-ID: 
> Content-Type: text/plain; charset="UTF-8"
> 
> Does anybody know if there is a precision difference when I use mpmath and
> take an expression:
> 
> from mpmath import *
> mp.dps = 100
> mu0 = [mpf('4') * pi * power(10, -7)
> 
> rather then:
> 
> mu0 = fprod([mpf('4'), pi, power(10, -7)])
> 
> ?
> 
> Thanks,
> -- Bernd
> 
> 
> --
> 
> Message: 5
> Date: Mon, 2 Feb 2009 14:46:18 -0800 (PST)
> From: Bernard Rankin 
> Subject: [Tutor] regex: not start with FOO
> To: Tutor@python.org
> Message-ID: <528538.84097...@web112218.mail.gq1.yahoo.com>
> Content-Type: text/plain; charset=us-ascii
> 
> Hello,
> 
> 
> I'd like to match any line that does not start with FOO.  (Using just a
> reg-ex rule)
> 
> 1) What is the effective difference between:
> 
> (?!^FOO).*
> 
> ^(?!FOO).*
> 
> 2) Is there a better way to do this?
> 
> 
> Thanks,
> :)
> 
> 
> 
>   
> 
> 
> 
> --
> 
> Message: 6
> Date: Mon, 02 Feb 2009 15:50:18 -0800
> From: "WM." 
> Subject: [Tutor] newton's sqrt formula
> To: tutor@python.org
> Message-ID: <498786ba.6090...@socal.rr.com>
> Content-Type: text/plain; charset=ISO-8859-1; format=flowed
> 
> # program to find square root
> square = input ('Please enter a number to be rooted, ')
> square = square * 1.0
> guess = input('Please guess at the root, ')
> guess = guess * 1.0
> newguess = 0.
> 
> while guess**2 != square:
>  # Newton's formula
>  newguess = guess - (guess * guess - square) / (guess * 2)
>  guess = newguess
>  guess**2 - square
> print
> print
> print guess, ' is the square root of ', square
> print
> print
> print 'bye'
> Last month there was a square root program discussed. I wondered if the 
> tide of my ignorance had receded enough that I could take a whack at 
> messing with it.
> I offer this rewrite for your critique. Can it be terser, faster, prettier?
> Thank you.
> 
> 
> 
> 
> --
> 
> Message: 7
> Date: Tue, 3 Feb 2009 00:44:27 -
> From: "Alan Gauld" 
> Subject: Re: [Tutor] newton's sqrt formula
> To: tutor@python.org
> Message-ID: 
> Content-Type: text/plain; format=flowed; charset="iso-8859-1";
>   reply-type=response
> 
> "WM."  wrote
> 
> > square = input ('Please enter a number to be rooted, ')
> > square = square * 1.0
> 
> Use raw_input() instead of input() and don't multiply
> by 1.0 - instead convert to float using float():
> 
> square = float( raw_input ('Please enter a number to be rooted, '))
> 
> > guess = input('Please guess at the root, ')
> > guess = guess * 1.0
> > newguess = 0.
> >
> > w

Re: [Tutor] Alarm Clock (suggestions please)

2009-02-03 Thread ukapache



John Fouhy wrote:
> 
> 2009/2/3 David :
>> while(doit):
>>mytime = list(time.localtime())
>>hour = mytime[3]
>>minute = mytime[4]
>>if hour == alarmhour and minute == alarmmin:
>>subprocess.call('mplayer -loop 9 ring.wav', shell=True)
>>sys.exit()
> 
> Hi David,
> 
> What you've written here is called a Busy Wait -- essentially, your
> program will be checking the local time as fast as it possibly can,
> which could be hundreds or thousands of times per second.  It will
> cause your CPU (or, at least, the core python is on) to run at 100%.
> 
> I imagine you don't actually care if your alarm is a few milliseconds
> late, so you could add a call to time.sleep(1) to the body of the
> loop. This will cause python to sleep for one second every iteration,
> thus allowing other programs to get some CPU time, and saving your
> power bill.
> 
> (in fact, since you're only specifying hour and minute for your alarm,
> you may as well sleep for 60 seconds each iteration)
> 
> Also, you could just write while(True).  Your control variable doit
> isn't actually doing anything in this program.
> 
> Regarding error checking, you could do tests to make sure the hour and
> minutes are in-range.  Perhaps you could add code to check whether the
> alarm time is more than a certain number of hours in the future.
> Depends how complex you want to make it.
> 
> (you could also inspect sys.argv -- this would allow you to specify
> the time on the command line, rather than requiring user input)
> 
> -- 
> John.
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 


Hi

This is my first post so please be gentle, have been teaching myself python
for the last two months

If you know the current local time  (time.localtime()) and the time you want
to wake up why not when you submit the program work out the difference
and make the alarm sleep for that time interval? 

Simon
-- 
View this message in context: 
http://www.nabble.com/Alarm-Clock-%28suggestions-please%29-tp21803518p21805118.html
Sent from the Python - tutor mailing list archive at Nabble.com.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Division problems

2009-02-03 Thread prasad rao
HelloI wrote a function named vertical to print string .printable characters
and ASCII values in a table.
1)It is swallowing some characters.
2)It output some characters  2 or 3 times.
3)It prints one column more than what I asked for.

It may be a division problem(floating point).
Its sibling called horizontal got no problems.
please examine it  and give suggestions and improvements to set it right.

#!usr\\bin\\env python
def horizontal(columns):
import string
n=0
v=string.printable
v=v.replace('\n','')
v=v.replace('\t','')
while n___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] newton's square root formula

2009-02-03 Thread Alan Gauld


"WM."  wrote 


# program to find square root
square = float(raw_input ("Please enter a number to be rooted, "))
guess = input("Please guess at the root, ")


Actually, I meant you should use raw_input here too...
input() is considered insecure and not recommended. 
(In Python v3 it has been removed from the language 
and raw_input renamed to input.)


--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] newton's square root formula

2009-02-03 Thread Andre Engels
On Tue, Feb 3, 2009 at 3:59 AM, WM.  wrote:
> # program to find square root
> square = float(raw_input ("Please enter a number to be rooted, "))
> guess = input("Please guess at the root, ")
> i = 0
> while guess**2 != square:
>i+=1
># Newton's formula
>guess = guess - (guess * guess - square) / (guess * 2)
>print i
> print "\n\n\n%s is the square root of %s" % (guess, square)
> print "\n%s loops were run." % (i)
> print "\n\n\nbye"
> #
>
>
> Here is my program, enhanced by Alan's good advice. The reason I wanted to
> re-write the other program was, it had a limited number of loops and I felt
> accuracy should be the measure. So, just now, I added a loop counter here
> and found that the formula is a little buggy. Make 'square = 7' and you will
> be in the 'i = 500' area before you can find ControlC.

The problem is the loop guard:

while guess**2 != square

There probably is no number guess for which Python has guess**2 == 7
exactly. You'll have to choose a certain precision, and look for a
number for which this closer than your chosen precision rather than a
number for which it is true exactly.

Change the guard to:

while abs(guess*guess-square) > 0.1:

and (choosing 1 as my initial guess) I got an answer after 6 iterations.

--
André Engels, andreeng...@gmail.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor