[Tutor] list of dict question

2010-10-08 Thread Roelof Wobben


Hello, 
 
I have this programm :
 
tournooi = [{'thuis': 'A','uit': "B",'thuisscore': 20, 'uitscore': 
15},{'thuis': 'C','uit': "D",'thuisscore': 80, 'uitscore': 40}]
stand = []
tussen_thuis = {}
tussen_uit = {}
for wedstrijd in tournooi :
if wedstrijd['thuis'] in stand :
print "True"
else :
tussen_thuis['ploeg']  = wedstrijd['thuis']
tussen_thuis['wedstrijden'] = 1
if wedstrijd['thuisscore']> wedstrijd['uitscore']:
tussen_thuis['punten'] = 2
else:
tussen_thuis['punten'] = 0 

tussen_thuis['voor'] = wedstrijd['thuisscore']
tussen_thuis ['tegen'] = wedstrijd['uitscore']
stand.append(tussen_thuis)
if wedstrijd['uit'] in stand :
print "True"
else :
tussen_uit['ploeg']  = wedstrijd['uit']
tussen_uit['wedstrijden'] = 1
if wedstrijd['thuisscore'] < wedstrijd['uitscore']:
tussen_uit['punten'] = 2
else:
tussen_uit['punten'] = 0 
tussen_uit['tegen'] = wedstrijd['thuisscore']
tussen_uit ['voor'] = wedstrijd['uitscore']
stand.append(tussen_uit)
 
It gives this output :
 
[{'punten': 2, 'tegen': 40, 'wedstrijden': 1, 'voor': 80, 'ploeg': 'C'}, 
{'punten': 0, 'tegen': 80, 'wedstrijden': 1, 'voor': 40, 'ploeg': 'D'}, 
{'punten': 2, 'tegen': 40, 'wedstrijden': 1, 'voor': 80, 'ploeg': 'C'}, 
{'punten': 0, 'tegen': 80, 'wedstrijden': 1, 'voor': 40, 'ploeg': 'D'}]

 
So the data of A and B are overwriting by C and D.
How can I prevent this ?
 
Roelof
 
 
  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list of dict question

2010-10-08 Thread Alan Gauld


"Roelof Wobben"  wrote


I have this programm :

tournooi = [{'thuis': 'A','uit': "B",'thuisscore': 20, 'uitscore': 
15},{'thuis': 'C','uit': "D",'thuisscore': 80, 'uitscore': 40}]

stand = []
tussen_thuis = {}
tussen_uit = {}


Here you create your dictionary objects.
You never create any more dictionary objects so these are the only 
ones you have.



for wedstrijd in tournooi :
   if wedstrijd['thuis'] in stand :
   print "True"


stand is a list of dictionaries so this will never be True.


   else :
   tussen_thuis['ploeg']  = wedstrijd['thuis']
   tussen_thuis['wedstrijden'] = 1
   if wedstrijd['thuisscore']> wedstrijd['uitscore']:
   tussen_thuis['punten'] = 2
   else:
   tussen_thuis['punten'] = 0

   tussen_thuis['voor'] = wedstrijd['thuisscore']
   tussen_thuis ['tegen'] = wedstrijd['uitscore']
   stand.append(tussen_thuis)


Here you append the dictionary into stand


   if wedstrijd['uit'] in stand :
   print "True"


But stand is a list with a dictionary inside so this test
cannot be true since wedstrijg['uit'] is not a dictionary.


   else :
   tussen_uit['ploeg']  = wedstrijd['uit']
   tussen_uit['wedstrijden'] = 1
   if wedstrijd['thuisscore'] < wedstrijd['uitscore']:
   tussen_uit['punten'] = 2
   else:
   tussen_uit['punten'] = 0
   tussen_uit['tegen'] = wedstrijd['thuisscore']
   tussen_uit ['voor'] = wedstrijd['uitscore']
   stand.append(tussen_uit)


Now you append a second dictionary to stand.

On the next iteration you overwrite those two dictionaries
with new values then append them to the list again.
So you wind up with 2 copies of the updated dictionaries.


So the data of A and B are overwriting by C and D.
How can I prevent this ?


You need to create new dictionaries for each iteration of the loop.
Move the dictionary creation lines inside the loop.

HTH,


--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list of dict question

2010-10-08 Thread Roelof Wobben




> To: tutor@python.org
> From: alan.ga...@btinternet.com
> Date: Fri, 8 Oct 2010 09:02:05 +0100
> Subject: Re: [Tutor] list of dict question
>
>
> "Roelof Wobben" wrote
>
>> I have this programm :
>>
>> tournooi = [{'thuis': 'A','uit': "B",'thuisscore': 20, 'uitscore':
>> 15},{'thuis': 'C','uit': "D",'thuisscore': 80, 'uitscore': 40}]
>> stand = []
>> tussen_thuis = {}
>> tussen_uit = {}
>
> Here you create your dictionary objects.
> You never create any more dictionary objects so these are the only
> ones you have.
>
>> for wedstrijd in tournooi :
>> if wedstrijd['thuis'] in stand :
>> print "True"
>
> stand is a list of dictionaries so this will never be True.
>
>> else :
>> tussen_thuis['ploeg'] = wedstrijd['thuis']
>> tussen_thuis['wedstrijden'] = 1
>> if wedstrijd['thuisscore']> wedstrijd['uitscore']:
>> tussen_thuis['punten'] = 2
>> else:
>> tussen_thuis['punten'] = 0
>>
>> tussen_thuis['voor'] = wedstrijd['thuisscore']
>> tussen_thuis ['tegen'] = wedstrijd['uitscore']
>> stand.append(tussen_thuis)
>
> Here you append the dictionary into stand
>
>> if wedstrijd['uit'] in stand :
>> print "True"
>
> But stand is a list with a dictionary inside so this test
> cannot be true since wedstrijg['uit'] is not a dictionary.
>
>> else :
>> tussen_uit['ploeg'] = wedstrijd['uit']
>> tussen_uit['wedstrijden'] = 1
>> if wedstrijd['thuisscore'] < wedstrijd['uitscore']:
>> tussen_uit['punten'] = 2
>> else:
>> tussen_uit['punten'] = 0
>> tussen_uit['tegen'] = wedstrijd['thuisscore']
>> tussen_uit ['voor'] = wedstrijd['uitscore']
>> stand.append(tussen_uit)
>
> Now you append a second dictionary to stand.
>
> On the next iteration you overwrite those two dictionaries
> with new values then append them to the list again.
> So you wind up with 2 copies of the updated dictionaries.
>
>> So the data of A and B are overwriting by C and D.
>> How can I prevent this ?
>
> You need to create new dictionaries for each iteration of the loop.
> Move the dictionary creation lines inside the loop.
>
> HTH,
>
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
>
> ___
> Tutor maillist - Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

 
Hello Alan, 
 
Thank you.
Now i can work on a script which can check if a team exist in standen.
 
Roelof
  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list of dict question

2010-10-08 Thread Francesco Loffredo

Il 08/10/2010 10.02, Alan Gauld ha scritto:


"Roelof Wobben"  wrote


I have this programm :

tournooi = [{'thuis': 'A','uit': "B",'thuisscore': 20, 'uitscore':

...

for wedstrijd in tournooi :
if wedstrijd['thuis'] in stand :
print "True"


stand is a list of dictionaries so this will never be True.
...

if wedstrijd['uit'] in stand :
print "True"


But stand is a list with a dictionary inside so this test
cannot be true since wedstrijg['uit'] is not a dictionary.

I'll say the same another way: you are searching an apple in a container 
of baskets, one of which MAY CONTAIN an apple. But you only see baskets, 
and none of those can BE an apple!
My two cents: the following might be still new for you, but this is a 
way to check if wedstrijd['thuis'] is in stand:


if wedstrijd['thuis'] in [u['ploeg'] for u in stand]

where you build a temporary list of 'ploeg's in stand and check whether 
wedstrijd['thuis'] is found there.



...
On the next iteration you overwrite those two dictionaries
with new values then append them to the list again.
So you wind up with 2 copies of the updated dictionaries.
...
This is difficult for me too: why does this happen? Or, more correctly, 
why should this happen? How can you save the current contents of a 
dictionary in a list, making sure that the saved values won't change if 
you update the dict?
You tell Roelof that the dictionary must be created at every loop, but 
if so, where goes the elegance of

myDictList.append(UpdateIt(myDict))
???

Francesco (puzzled)
Nessun virus nel messaggio in uscita.
Controllato da AVG - www.avg.com
Versione: 9.0.862 / Database dei virus: 271.1.1/3182 -  Data di rilascio: 
10/07/10 08:34:00
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Rounding a Python float to the nearest half integer

2010-10-08 Thread Sithembewena Lloyd Dube
Hi folks,

Supposing I had the float 4.4348 and I wished to round it off to the nearest
half-integer upwards or downwards, how would I go about it?

Many thanks...

-- 
Regards,
Sithembewena Lloyd Dube
http://www.lloyddube.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Rounding a Python float to the nearest half integer

2010-10-08 Thread Sithembewena Lloyd Dube
I realise that one cannot have a half integer :) I meant how would one round
off to the first decimal nearest to either 0.5, or a whole number.

Ugh...does anyone get what I'm trying to articulate? :)

On Fri, Oct 8, 2010 at 2:51 PM, Sithembewena Lloyd Dube
wrote:

> Hi folks,
>
> Supposing I had the float 4.4348 and I wished to round it off to the
> nearest half-integer upwards or downwards, how would I go about it?
>
> Many thanks...
>
> --
> Regards,
> Sithembewena Lloyd Dube
> http://www.lloyddube.com
>



-- 
Regards,
Sithembewena Lloyd Dube
http://www.lloyddube.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Rounding a Python float to the nearest half integer

2010-10-08 Thread Wayne Werner
On Fri, Oct 8, 2010 at 7:51 AM, Sithembewena Lloyd Dube
wrote:

> Hi folks,
>
> Supposing I had the float 4.4348 and I wished to round it off to the
> nearest half-integer upwards or downwards, how would I go about it?
>

You can use round:

round(4.4348) -> 4.0

But if you want to specify the behavior you can do something like this:

x = 4.4348
if x % 1 >= 0.5:
   x = x/1+1
else:
   x = x/1

HTH,
Wayne
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Rounding a Python float to the nearest half integer

2010-10-08 Thread Evert Rol
> I realise that one cannot have a half integer :) I meant how would one round 
> off to the first decimal nearest to either 0.5, or a whole number.
> 
> Ugh...does anyone get what I'm trying to articulate? :)

Multiply by 2, round(), divide by 2?


> 
> On Fri, Oct 8, 2010 at 2:51 PM, Sithembewena Lloyd Dube  
> wrote:
> Hi folks,
> 
> Supposing I had the float 4.4348 and I wished to round it off to the nearest 
> half-integer upwards or downwards, how would I go about it?
> 
> Many thanks...
> 
> --
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Rounding a Python float to the nearest half integer

2010-10-08 Thread Joel Goldstick
On Fri, Oct 8, 2010 at 9:00 AM, Evert Rol  wrote:

> > I realise that one cannot have a half integer :) I meant how would one
> round off to the first decimal nearest to either 0.5, or a whole number.
> >
> > Ugh...does anyone get what I'm trying to articulate? :)
>
> Multiply by 2, round(), divide by 2?
>

That sounds like a good idea:

>
> >>> n = [1.0 + x/10.0 for x in range(10)]  # get some numbers to test
> >>> n
> [1.0, 1.1001, 1.2, 1.3, 1.3999, 1.5,
> 1.6001, 1.7, 1.8, 1.8999]
> >>> r = [round(2*x)/2.0 for x in n]   # double, round, then divide by 2.0
> >>> r
> [1.0, 1.0, 1.0, 1.5, 1.5, 1.5, 1.5, 1.5, 2.0, 2.0]
> >>>
>
>
-- 
Joel Goldstick
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Rounding a Python float to the nearest half integer

2010-10-08 Thread Sithembewena Lloyd Dube
Thanks everyone,

I need to round to the nearest half (finally occured).

Made some chnages to Wayne's code as follows:

x = 4.4348
if x % 1 >= 0.5:
   round(x) # gives 5.0 if  the the value of the expression x % 1 exceeds
0.5
else:
   x = round(x) + 0.5 # gives 4.5, as in this case.

Many thanks!



On Fri, Oct 8, 2010 at 3:00 PM, Evert Rol  wrote:

> > I realise that one cannot have a half integer :) I meant how would one
> round off to the first decimal nearest to either 0.5, or a whole number.
> >
> > Ugh...does anyone get what I'm trying to articulate? :)
>
> Multiply by 2, round(), divide by 2?
>
>
> >
> > On Fri, Oct 8, 2010 at 2:51 PM, Sithembewena Lloyd Dube <
> zebr...@gmail.com> wrote:
> > Hi folks,
> >
> > Supposing I had the float 4.4348 and I wished to round it off to the
> nearest half-integer upwards or downwards, how would I go about it?
> >
> > Many thanks...
> >
> > --
>



-- 
Regards,
Sithembewena Lloyd Dube
http://www.lloyddube.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Rounding a Python float to the nearest half integer

2010-10-08 Thread Sithembewena Lloyd Dube
@Evert, I didn't figure out that your response was a solution, thought it
was a question. Must be coffee time :P

I tried it and, for instance, the rounded value (9) / 2 gave me 4.0 Couldn't
get it until I noticed that @Joel divided the roudned figure by a decimal
2.0. That gave 4.5, which is what I was looking for.

Thanks to all.

On Fri, Oct 8, 2010 at 3:35 PM, Joel Goldstick wrote:

>
>
> On Fri, Oct 8, 2010 at 9:00 AM, Evert Rol  wrote:
>
>> > I realise that one cannot have a half integer :) I meant how would one
>> round off to the first decimal nearest to either 0.5, or a whole number.
>> >
>> > Ugh...does anyone get what I'm trying to articulate? :)
>>
>> Multiply by 2, round(), divide by 2?
>>
>
> That sounds like a good idea:
>
>>
>> >>> n = [1.0 + x/10.0 for x in range(10)]  # get some numbers to test
>> >>> n
>> [1.0, 1.1001, 1.2, 1.3, 1.3999, 1.5,
>> 1.6001, 1.7, 1.8, 1.8999]
>> >>> r = [round(2*x)/2.0 for x in n]   # double, round, then divide by 2.0
>> >>> r
>> [1.0, 1.0, 1.0, 1.5, 1.5, 1.5, 1.5, 1.5, 2.0, 2.0]
>> >>>
>>
>>
> --
> Joel Goldstick
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
Regards,
Sithembewena Lloyd Dube
http://www.lloyddube.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] PYTHON QUOTES ISSUE

2010-10-08 Thread Susana Iraiis Delgado Rodriguez
Hi Alan:

The ouput is coming from a cicle and some functions that I vae to do to
execute an ogr2ogr command, in this output I ask the user for the name of a
file and then make a module to get to the subprocess part:

import shlex, subprocess, sys
from dbf import *
def process():
#Read dbfile status 100%
 a = open ("capas.txt","w+")
 print 'Enter the shapefile name'
 b = raw_input()
 print '\n'
dbf = Dbf(b+".dbf",new=False)

for rec in dbf:
 for fldName in dbf.fieldNames:
 if fldName == 'LAYER':
 l=()
 l=rec[fldName]
 a.write(l)
 a.write("\n")
a.close()

##Eliminate duplicate lines from the txt into a new txt, status:100%
  a = open ("capas.txt","r")
  catalogo = open ("unico.txt","w")
  unique = set(a.read().split("\n"))
  catalogo.write("".join([line + "\n" for line in unique]))
  catalogo.close()
  a.close()

##Execute ogr2ogr command, status:75%
 for line in open("unico.txt", "r"):
p = subprocess.Popen(['C:/Archivos de
programa/FWTools2.4.7/bin/ogr2ogr', line+'.shp', '-where',
"\"LAYER='"+line+"'\"" , b+'.shp'])

But when I executed it shows me an error in the layer's name:

>>> ERROR 1: Failed to identify field:LAYER=
ERROR 1: Failed to create file .shp file.
ERROR 4: Failed to open Shapefile `0
.shp'.

I think the erros showed up because some of the layer's values are 0 and '
', and obsviously you can't create a file from nothing on it. But I don`t
know how to validate if a layer's value is equals to 0 or ' ', any idea what
I'm doing wrong or how to fix it?


2010/10/7 Susana Iraiis Delgado Rodriguez 

> Hello taserian and Antonio!
>
> Thank you both for taking the time to answer my question. With taserian's
> code it gives me the next output:
> C... ogr2ogr T21-PUENTESshp -where "LAYER=T21-PUENTES"
> tapalpa_05_plani_line.shp
> but the output I need is:
> C... ogr2ogr T21-PUENTESshp -where "LAYER=' T21-PUENTES' "
> tapalpa_05_plani_line.shp
>
> I did the Antonio's suggested corrections, and I got the string I wanted,
> now the problem is that my subprocess doesn't work properly, I'll give a
> look and see whats wrong with it.
>
>
> 2010/10/7 taserian 
>
>  On Thu, Oct 7, 2010 at 12:48 PM, taserian  wrote:
>>
>>> I'm adding some line breaks to make your text a little more readable.
>>>
>>> On Thu, Oct 7, 2010 at 9:55 AM, Susana Iraiis Delgado Rodriguez <
>>> susana.delgad...@utzmg.edu.mx> wrote:
>>>
>>>  Hello members:

 How can I write a statement to execute the following:

>>>
>>>
 C:/Archivos de programa/FWTools2.4.7/bin/ogr2ogr R1G-GEODESIA.shp -where
 "LAYER = 'R1G-GEODESIA'" tapalpa_05_plani_point.dbf

>>>
>>>
 I want my uotput to look like this.
 Instead I'm getting this

>>>
>>>
 C:/Archivos de programa/FWTools2.4.7/bin/ogr2ogr T21-PUENTES.shp -where
 LAYER=+line tapalpa_05_plani_line.shp

>>>
>>>
 In miy code line is a string given by the user:

 for line in open("unico.txt", "r").readlines():
  p = subprocess.Popen(['C:/Archivos de
 programa/FWTools2.4.7/bin/ogr2ogr', line+'.shp', '-where', "LAYER='line'",
 b+'.shp'])

 Any suggestions?

>>>
>>> Without knowing specifics about what the subprocess.Popen function is
>>> expecting as parameters, I can only speculate, but it seems that the
>>> following *might* work (for extremely generous values of "*might*"):
>>>
>>>  for line in open("unico.txt", "r").readlines():
>>>  p = subprocess.Popen(['C:/Archivos de
>>> programa/FWTools2.4.7/bin/ogr2ogr', line+'.shp', '-where', "\"LAYER='" +
>>> line + "'\"", b+'.shp'])
>>>
>>> Details about where the changes are:
>>> "\"LAYER='" + line + "'\""
>>>
>>
>> Begin corrections (corrections start with a *)
>>
>>   Quote to begin the literal: "
>>> An escaped quote (1) so that there's a quote inside the literal: \"
>>> Some of the text that's meant to be unchanging: LAYER=
>>>
>> *Single Quote (2) to be included in the literal (which doesn't need to be
>> escaped): '
>>
>>>  Close Quote: "
>>>
>>  Add the content of the variable "line" from the unico.txt file:  + line
>>> +
>>>
>> *Add another literal, composed of the single quote that closes (2) above,
>> then the closing escaped quote to close (1) : "'\""
>>
>>
>>>
>>> See if this works, and let us know how it turns out.
>>>
>>> Antonio Rodriguez
>>>
>>
>> End of corrections.
>>
>> Antonio Rodriguez
>>
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] PYTHON QUOTES ISSUE

2010-10-08 Thread Susana Iraiis Delgado Rodriguez
Besides, If I print the query, I have the next output:

C:/Archivos de programa/FWTools2.4.7/bin/ogr2ogr U3B-BARDA

.shp -where "LAYER='U3B-BARDA

'" tapalpa_05_plani_line.shp

C:/Archivos de programa/FWTools2.4.7/bin/ogr2ogr N2H-TEMP

.shp -where "LAYER='N2H-TEMP

'" tapalpa_05_plani_line.shp

C:/Archivos de programa/FWTools2.4.7/bin/ogr2ogr U3C-CERCA

.shp -where "LAYER='U3C-CERCA

'" tapalpa_05_plani_line.shp..
I thought it was a console print issue, but when I run the module from
Eclipse, it shows the same enter space, so I think it maybe that the line is
not together as it is a statement!!
2010/10/8 Susana Iraiis Delgado Rodriguez 

> Hi Alan:
>
> The ouput is coming from a cicle and some functions that I vae to do to
> execute an ogr2ogr command, in this output I ask the user for the name of a
> file and then make a module to get to the subprocess part:
>
> import shlex, subprocess, sys
> from dbf import *
> def process():
> #Read dbfile status 100%
>  a = open ("capas.txt","w+")
>  print 'Enter the shapefile name'
>  b = raw_input()
>  print '\n'
> dbf = Dbf(b+".dbf",new=False)
>
> for rec in dbf:
>  for fldName in dbf.fieldNames:
>  if fldName == 'LAYER':
>  l=()
>  l=rec[fldName]
>  a.write(l)
>  a.write("\n")
> a.close()
>
> ##Eliminate duplicate lines from the txt into a new txt, status:100%
>   a = open ("capas.txt","r")
>   catalogo = open ("unico.txt","w")
>   unique = set(a.read().split("\n"))
>   catalogo.write("".join([line + "\n" for line in unique]))
>   catalogo.close()
>   a.close()
>
> ##Execute ogr2ogr command, status:75%
>  for line in open("unico.txt", "r"):
>
> p = subprocess.Popen(['C:/Archivos de
> programa/FWTools2.4.7/bin/ogr2ogr', line+'.shp', '-where',
> "\"LAYER='"+line+"'\"" , b+'.shp'])
>
> But when I executed it shows me an error in the layer's name:
>
> >>> ERROR 1: Failed to identify field:LAYER=
> ERROR 1: Failed to create file .shp file.
> ERROR 4: Failed to open Shapefile `0
> .shp'.
>
> I think the erros showed up because some of the layer's values are 0 and '
> ', and obsviously you can't create a file from nothing on it. But I don`t
> know how to validate if a layer's value is equals to 0 or ' ', any idea what
> I'm doing wrong or how to fix it?
>
>
> 2010/10/7 Susana Iraiis Delgado Rodriguez 
>
>  Hello taserian and Antonio!
>>
>> Thank you both for taking the time to answer my question. With taserian's
>> code it gives me the next output:
>> C... ogr2ogr T21-PUENTESshp -where "LAYER=T21-PUENTES"
>> tapalpa_05_plani_line.shp
>> but the output I need is:
>> C... ogr2ogr T21-PUENTESshp -where "LAYER=' T21-PUENTES' "
>> tapalpa_05_plani_line.shp
>>
>> I did the Antonio's suggested corrections, and I got the string I wanted,
>> now the problem is that my subprocess doesn't work properly, I'll give a
>> look and see whats wrong with it.
>>
>>
>> 2010/10/7 taserian 
>>
>>  On Thu, Oct 7, 2010 at 12:48 PM, taserian  wrote:
>>>
 I'm adding some line breaks to make your text a little more readable.

 On Thu, Oct 7, 2010 at 9:55 AM, Susana Iraiis Delgado Rodriguez <
 susana.delgad...@utzmg.edu.mx> wrote:

  Hello members:
>
> How can I write a statement to execute the following:
>


> C:/Archivos de programa/FWTools2.4.7/bin/ogr2ogr R1G-GEODESIA.shp
> -where "LAYER = 'R1G-GEODESIA'" tapalpa_05_plani_point.dbf
>


> I want my uotput to look like this.
> Instead I'm getting this
>


> C:/Archivos de programa/FWTools2.4.7/bin/ogr2ogr T21-PUENTES.shp -where
> LAYER=+line tapalpa_05_plani_line.shp
>


> In miy code line is a string given by the user:
>
> for line in open("unico.txt", "r").readlines():
>  p = subprocess.Popen(['C:/Archivos de
> programa/FWTools2.4.7/bin/ogr2ogr', line+'.shp', '-where', "LAYER='line'",
> b+'.shp'])
>
> Any suggestions?
>

 Without knowing specifics about what the subprocess.Popen function is
 expecting as parameters, I can only speculate, but it seems that the
 following *might* work (for extremely generous values of "*might*"):

  for line in open("unico.txt", "r").readlines():
  p = subprocess.Popen(['C:/Archivos de
 programa/FWTools2.4.7/bin/ogr2ogr', line+'.shp', '-where', "\"LAYER='" +
 line + "'\"", b+'.shp'])

 Details about where the changes are:
 "\"LAYER='" + line + "'\""

>>>
>>> Begin corrections (corrections start with a *)
>>>
>>>   Quote to begin the literal: "
 An escaped quote (1) so that there's a quote inside the literal: \"
 Some of the text that's meant to be unchanging: LAYER=

>>> *Single Quote (2) to be included in the literal (which doesn't need to be
>>> escaped): '
>>>
  Close Quote: "

>>>  Add the content of the variable "line" from the unico.txt file:  + line
>>>

Re: [Tutor] Rounding a Python float to the nearest half integer

2010-10-08 Thread Evert Rol
> @Evert, I didn't figure out that your response was a solution, thought it was 
> a question. Must be coffee time :P
> 
> I tried it and, for instance, the rounded value (9) / 2 gave me 4.0 Couldn't 
> get it until I noticed that @Joel divided the roudned figure by a decimal 
> 2.0. That gave 4.5, which is what I was looking for.

How do you get a rounded value of 9 (integer)? Round() returns a float, afaik; 
ie, you wouldn't the the 2.0, but just 2. (In fact, your return value is 4.0, 
which for integer division wouldn't work. So something was odd there, but I 
can't think of what.)

Also, perhaps better to use
from __future__ import division
to prevent these mistakes.

Cheers,

  Evert


> > I realise that one cannot have a half integer :) I meant how would one 
> > round off to the first decimal nearest to either 0.5, or a whole number.
> >
> > Ugh...does anyone get what I'm trying to articulate? :)
> 
> Multiply by 2, round(), divide by 2?
> 
> That sounds like a good idea: 
> 
> >>> n = [1.0 + x/10.0 for x in range(10)]  # get some numbers to test
> >>> n
> [1.0, 1.1001, 1.2, 1.3, 1.3999, 1.5, 
> 1.6001, 1.7, 1.8, 1.8999]
> >>> r = [round(2*x)/2.0 for x in n]   # double, round, then divide by 2.0
> >>> r
> [1.0, 1.0, 1.0, 1.5, 1.5, 1.5, 1.5, 1.5, 2.0, 2.0]
> >>> 
> 
> 
> -- 
> Joel Goldstick
> 
> 
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
> 
> 
> 
> 
> -- 
> Regards,
> Sithembewena Lloyd Dube
> http://www.lloyddube.com
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] FW: list of dict question

2010-10-08 Thread Roelof Wobben




> From: rwob...@hotmail.com
> To: f...@libero.it
> Subject: RE: [Tutor] list of dict question
> Date: Fri, 8 Oct 2010 14:53:53 +
>
>
>
>
> 
> Date: Fri, 8 Oct 2010 13:40:04 +0200
> From: f...@libero.it
> To: tutor@python.org
> Subject: Re: [Tutor] list of dict question
>
>
> Il 08/10/2010 10.02, Alan Gauld ha scritto:
>>
>> "Roelof Wobben" wrote
>>
>>> I have this programm :
>>>
>>> tournooi = [{'thuis': 'A','uit': "B",'thuisscore': 20, 'uitscore':
>> ...
>>> for wedstrijd in tournooi :
>>> if wedstrijd['thuis'] in stand :
>>> print "True"
>>
>> stand is a list of dictionaries so this will never be True.
>>...
>>> if wedstrijd['uit'] in stand :
>>> print "True"
>>
>> But stand is a list with a dictionary inside so this test
>> cannot be true since wedstrijg['uit'] is not a dictionary.
>>
> I'll say the same another way: you are searching an apple in a container
> of baskets, one of which MAY CONTAIN an apple. But you only see baskets,
> and none of those can BE an apple!
> My two cents: the following might be still new for you, but this is a
> way to check if wedstrijd['thuis'] is in stand:
>
> if wedstrijd['thuis'] in [u['ploeg'] for u in stand]
>
> where you build a temporary list of 'ploeg's in stand and check whether
> wedstrijd['thuis'] is found there.
>
>>...
>> On the next iteration you overwrite those two dictionaries
>> with new values then append them to the list again.
>> So you wind up with 2 copies of the updated dictionaries.
>> ...
> This is difficult for me too: why does this happen? Or, more correctly,
> why should this happen? How can you save the current contents of a
> dictionary in a list, making sure that the saved values won't change if
> you update the dict?
> You tell Roelof that the dictionary must be created at every loop, but
> if so, where goes the elegance of
> myDictList.append(UpdateIt(myDict))
> ???
>
> Francesco (puzzled)
>
> ___
> Tutor maillist - Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

Hello Franceso,

Thank you for the answer.

Now find ot how i can find the dict which contains a team.
I thinking now of something like this.

teller = 1
  For wedstrijd in tournooi :
if wedstrijd['thuis'] != stand ['ploeg'] :
teller = teller + 1
stand[teller]['wedstrijd'] += 1

Could this work ?

Roelof
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Non-ASCII

2010-10-08 Thread Shawn Matlock
Evert,

You're guess was right, copying the code from the email message worked. My IDE 
- Eclipse/PyDev - must have been hiding the control character. I had tried 
copying my code out to a text editor and back before asking for help, but it 
didn't work. Perhaps I didn't "select all" before pasting the code back.

Thank you for the explanation.

Shawn

-Original Message-
From: Evert Rol [mailto:evert@gmail.com] 
Sent: Thursday, October 07, 2010 12:34 PM
To: Shawn Matlock
Cc: tutor@python.org
Subject: Re: [Tutor] Non-ASCII

> I'm going through an online tutorial for Jython (www.jython.org). I can't 
> find a place to ask a question on that site so I thought I'd try here. I 
> believe the code is supposed to traverse a directory, identifying file types. 
> The script is failing with the following message:
> 
>  File "", line None
> SyntaxError: Non-ASCII character in file 
> 'H:\workspace\test\src\root\nested\example.py', but no encoding declared; see 
> http://www.python.org/peps/pep-0263.html for details

Normally, this (obviously) means you have some non-ASCII characters (accented 
characters would already do this) in your source code. Since this is just a 
byte code at the lowest level, it needs to be decoded into something sensible, 
which you specify using an encoding. Since Python refuses to guess which 
encoding you want to use (the same character code could result in totally 
different characters for different encodings), it's bailing out instead of 
continuing (the exception being that by default, the Python interpreter assumes 
your encoding is ASCII, and happily proceeds with that until it comes across a 
character code outside the ASCII range).

In your code below, however, I don't see any non-ASCII characters. So my best 
guess is that there is some invisible control-character outside the ASCII range 
that's causing this error message. 
This could happen because of a particular type of text-editor/IDE you're using.

The odd thing I find about the SyntaxError is actually that there is no line 
number mentioned. In fact, 'File "", line None' is a very weird 
indication for telling where the error occurred. Might again be something to do 
with your IDE.

I've tried your code by simply copy-pasting, and that works fine for me. So the 
control-character didn't reach my mail program. In which case you could try to 
copy-past the code from this reply into a new file and see if that's gotten rid 
of the control-character (presuming that caused the problem).

Of course, if it's eg a known problem in Jython, I can't really tell you, 
because I simply don't know Jython. But try clean code for a start.

HTH,

  Evert


> 
> Thank you,
> Shawn
> 
> 

import os, sys 
from stat import *

def walktree(top, callback):
   '''recursively descend the directory tree rooted at top,
   calling the callback function for each regular file'''
   for f in os.listdir(top):
   pathname = os.path.join(top, f) 
   mode = os.stat(pathname)[ST_MODE] 
   if S_ISDIR(mode):
   # It's a directory, recurse into it 
   walktree(pathname, callback)
   elif S_ISREG(mode):
   # It's a file, call the callback function 
   callback(pathname)
   else:
   # Unknown file type, print a message 
   print 'Skipping %s' % pathname

def visitfile(file):
   print 'visiting', file

if __name__ == '__main__':
   walktree(sys.argv[1], visitfile)

> 
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] PYTHON QUOTES ISSUE

2010-10-08 Thread taserian
On Fri, Oct 8, 2010 at 10:27 AM, Susana Iraiis Delgado Rodriguez <
susana.delgad...@utzmg.edu.mx> wrote:

> Hi Alan:
>
> The ouput is coming from a cicle and some functions that I vae to do to
> execute an ogr2ogr command, in this output I ask the user for the name of a
> file and then make a module to get to the subprocess part:
>




> ##Eliminate duplicate lines from the txt into a new txt, status:100%
>   a = open ("capas.txt","r")
>   catalogo = open ("unico.txt","w")
>   unique = set(a.read().split("\n"))
>   catalogo.write("".join([line + "\n" for line in unique]))
>   catalogo.close()
>   a.close()
>

I don't see how this is eliminating duplicate lines. To me it looks like
it's just copying the contents of capas.txt into unico.txt and adding extra
\n (line breaks), which might be what's breaking your next line.


>
> ##Execute ogr2ogr command, status:75%
>  for line in open("unico.txt", "r"):
> p = subprocess.Popen(['C:/Archivos de
> programa/FWTools2.4.7/bin/ogr2ogr', line+'.shp', '-where',
> "\"LAYER='"+line+"'\"" , b+'.shp'])
>
> But when I executed it shows me an error in the layer's name:
>
> >>> ERROR 1: Failed to identify field:LAYER=
> ERROR 1: Failed to create file .shp file.
> ERROR 4: Failed to open Shapefile `0
> .shp'.
>
> I think the erros showed up because some of the layer's values are 0 and '
> ', and obsviously you can't create a file from nothing on it. But I don`t
> know how to validate if a layer's value is equals to 0 or ' ', any idea what
> I'm doing wrong or how to fix it?
>

Also, in your next e-mail, I noticed you're getting carriage returns (line
breaks in your output). Since you're adding those line breaks above, you
want to remove them before using them somewhere else.

p = subprocess.Popen(['C:/Archivos de programa/FWTools2.4.7/bin/ogr2ogr',
line.replace("\n", "") +'.shp', '-where', "\"LAYER='"+ line.replace("\n",
"") +"'\"" , b+'.shp'])


In the code above, I've changed the references to the variable *line* so
that the \n's are replaced by 0-length strings. That should remove them from
the Popen arguments.

Antonio Rodriguez
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] FW: list of dict question

2010-10-08 Thread Francesco Loffredo

On 08/10/2010 16.54, Roelof Wobben wrote:

...
Hello Franceso,

Thank you for the answer.

You're welcome.


Now find ot how i can find the dict which contains a team.
I thinking now of something like this.

teller = 1
   For wedstrijd in tournooi :
 if wedstrijd['thuis'] != stand ['ploeg'] :
 teller = teller + 1
stand[teller]['wedstrijd'] += 1

Could this work ?
I'm afraid it cannot, Roelof. In your loop, you are searching many teams 
(if I translated well, I don't even know what language you speak) in the 
wrong place. If you try the following at a Python shell prompt:



stand =
[{'punten': 2, 'tegen': 40, 'wedstrijden': 1, 'voor': 80, 'ploeg': 'C'}, 
{'punten': 0, 'tegen': 80, 'wedstrijden': 1, 'voor': 40, 'ploeg': 'D'}, 
{'punten': 2, 'tegen': 40, 'wedstrijden': 1, 'voor': 80, 'ploeg': 'C'}, 
{'punten': 0, 'tegen':80, 'wedstrijden': 1, 'voor': 40, 'ploeg': 'D'}]

stand['ploeg']

Traceback (most recent call last):
  File "", line 1, in 
TypeError: list indices must be integers, not str




you'll see that stand['ploeg'] doesn't exist. What does exist is, for 
example, stand[0]['ploeg'], or stand[3]['ploeg']. This is because stand 
is a list, and it just contains dictionaries. See my previous example 
with apples and baskets. So, if you are searching stand for all elements 
NOT CONTAINING a given team, you should search wedstrijd['thuis'] in the 
'ploeg' element of EACH element of stand, something like:


teller = 1
for wedstrijd in tournooi:
  for roelof in range(len(stand)):
if wedstrijd['thuis'] != stand[roelof]['ploeg']:
  teller = teller + 1


stand[teller]['wedstrijd'] += 1


This cannot work, either, because no element in stand contains an 
element whose key is 'wedstrijd', and I don't understand why you should 
update that element of stand whose index is teller. In this program, 
teller ends up containing the TOTAL number of elements in stand not 
containing the "thuis" of EACH "wedstrijd" of turnooi. I don't 
understand what do you want to do with this statement. It's very 
probable that teller becomes much larger than len(stand), and so 
stand[teller] will raise an exception...




Roelof  


Francesco
Nessun virus nel messaggio in uscita.
Controllato da AVG - www.avg.com
Versione: 9.0.862 / Database dei virus: 271.1.1/3182 -  Data di rilascio: 
10/07/10 08:34:00
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] IDE for Python

2010-10-08 Thread Steven D'Aprano
On Fri, 8 Oct 2010 02:23:27 am Juan Jose Del Toro wrote:
> Dear List;
>
> In your experience what is the best IDE for Python?

None of them. 

I use a good editor in one window (I prefer Kate for larger projects, 
although Kwrite is good enough for single modules or scripts) and a 
good xterm in another. I can open as many tabs as I need in the xterm. 
I have at least one interactive Python session open, plus another tab 
for running unit tests or doc tests. The only thing I miss having is 
integrated version control, and consequently I tend to be lazy and 
avoid using it unless forced.



-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] WRITING XLS FROM OS.WALK()

2010-10-08 Thread Susana Iraiis Delgado Rodriguez
Hello members:
I developed a Python module to make a list which contains all the files
ending with .shp and .dbf extensions, I have solved this already, but now I
want to write an excel file from it. The file should show the full path from
the found files. This is the code:

import os
a = open ("directorio.xls","w")
allfiles = [] #store all files found
 for root,dir,files in os.walk("C:\\"):
   filelist = [ os.path.join(root,fi) for fi in files if
fi.endswith(".shp") or fi.endswith(".dbf") ]
   for f in filelist:
allfiles.append(f)
for i in allfiles:
  print i
  a.write(i)
  a.write("\n")

With the code above, I have the print and the .xls file with
this information in it, the issue here is that my file doesn't have the
complete information that I got in the console. Any idea? The last line from
excel is C:\Python26
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] WRITING XLS FROM OS.WALK()

2010-10-08 Thread Walter Prins
On 8 October 2010 20:34, Susana Iraiis Delgado Rodriguez <
susana.delgad...@utzmg.edu.mx> wrote:

> Hello members:
> I developed a Python module to make a list which contains all the files
> ending with .shp and .dbf extensions, I have solved this already, but now I
> want to write an excel file from it. The file should show the full path from
> the found files. This is the code:
>
> import os
> a = open ("directorio.xls","w")
>

Excel (.xls) is not a text format.  What you've written opens
"directorio.xls" as a text file.

If you want to write an Excel format file, have a look at the xlwt (and the
xlrt for reading) Python modules. See http://www.python-excel.org/

Walter
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Rounding a Python float to the nearest half integer

2010-10-08 Thread Wayne Werner
On Fri, Oct 8, 2010 at 7:58 AM, Sithembewena Lloyd Dube
wrote:

> I realise that one cannot have a half integer :) I meant how would one
> round off to the first decimal nearest to either 0.5, or a whole number.
>
> Ugh...does anyone get what I'm trying to articulate? :)


sample input/output cases are always useful.

-Wayne
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] WRITING XLS FROM OS.WALK()

2010-10-08 Thread Emile van Sebille

On 10/8/2010 12:34 PM Susana Iraiis Delgado Rodriguez said...

Hello members:
I developed a Python module to make a list which contains all the files
ending with .shp and .dbf extensions, I have solved this already, but now I
want to write an excel file from it. The file should show the full path from
the found files. This is the code:

import os
a = open ("directorio.xls","w")
allfiles = [] #store all files found
  for root,dir,files in os.walk("C:\\"):
filelist = [ os.path.join(root,fi) for fi in files if
fi.endswith(".shp") or fi.endswith(".dbf") ]
for f in filelist:
 allfiles.append(f)
for i in allfiles:
   print i
   a.write(i)
   a.write("\n")

With the code above, I have the print and the .xls file with
this information in it, the issue here is that my file doesn't have the
complete information that I got in the console. Any idea? The last line from
excel is C:\Python26



You may find that finishing with a.flush() and a.close() fixes your problem.

Also, it appears that you're doing more than is required -- 
specifically, looping through filelist appending its members to allfiles 
can be done more simply with append, so where you're saying:


filelist = [...

you could say

allfiles.extend([...

and forget about filelist entirely.

HTH,

Emile


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] WRITING XLS FROM OS.WALK()

2010-10-08 Thread Hilton Fernandes
Hi !

Being Python as rich in libraries, probably there's already a library
to create .XLS files.

Before finding that, you can try the CSV format: simply put a comma to
separate any fields you want in your values.

And of course, a comma will finish your line.

That way, Excel or any other spreadsheet program will understand what
you want them to understand.

All the best,
hilton

On Fri, Oct 8, 2010 at 6:08 PM, Walter Prins  wrote:
>
>
> On 8 October 2010 20:34, Susana Iraiis Delgado Rodriguez
>  wrote:
>>
>> Hello members:
>> I developed a Python module to make a list which contains all the files
>> ending with .shp and .dbf extensions, I have solved this already, but now I
>> want to write an excel file from it. The file should show the full path from
>> the found files. This is the code:
>>
>> import os
>> a = open ("directorio.xls","w")
>
>
> Excel (.xls) is not a text format.  What you've written opens
> "directorio.xls" as a text file.
>
> If you want to write an Excel format file, have a look at the xlwt (and the
> xlrt for reading) Python modules. See http://www.python-excel.org/
>
> Walter
>
> ___
> Tutor maillist  -  tu...@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] WRITING XLS FROM OS.WALK()

2010-10-08 Thread Steven D'Aprano
On Sat, 9 Oct 2010 06:34:44 am Susana Iraiis Delgado Rodriguez wrote:
> Hello members:
> I developed a Python module to make a list which contains all the
> files ending with .shp and .dbf extensions, I have solved this
> already, 


I'm sorry to tell you that you've just reinvented the wheel. This was 
already solved, a long, long time ago. It is called the glob module:

>>> import glob
>>> glob.glob("/home/steve/*.jpg")
['/home/steve/hoversonic.jpg', '/home/steve/seperated_at_birth.jpg']
>>> glob.glob("/home/steve/*.txt")
['/home/steve/woss.txt', '/home/steve/file.txt', '/home/steve/post.txt']


You should use that. It works, it is tested and thoroughly debugged, and 
it is powerful.


> but now I want to write an excel file from it. The file 
> should show the full path from the found files.


Excel files are a proprietary, secret, binary file format. There is a 
Python project to allow reading and writing Excel files, but since it 
has to reverse-engineer the secret format, there's no guarantee that it 
will work. Having said that, I believe that it is very reliable, but 
I've never used it myself.

Google on "python read write excel files" for more information.

However, if your only aim is to make the data available to Excel, and 
you don't care what sort of file you use, the best way is the standard 
interchange format between spreadsheet applications, the comma-
separated value file, or CSV. This is a plain-text file, and Python 
comes with a module for reading and writing them. From the interactive 
interpreter, run this for more information:

import csv
help(csv)



> This is the code: 
>
> import os
> a = open ("directorio.xls","w")

Just because you name a file .xls doesn't make it an actual Excel file, 
any more than taking a JPEG and renaming it "word.exe" would turn it 
into the Microsoft Word application.


> allfiles = [] #store all files found
>  for root,dir,files in os.walk("C:\\"):
>filelist = [ os.path.join(root,fi) for fi in files if
> fi.endswith(".shp") or fi.endswith(".dbf") ]


This isn't your actual code. I know this, because the indentation is 
broken and it gives a syntax error.

>for f in filelist:
> allfiles.append(f)

This is better written as:

allfiles.extend(filelist)


but of course it is better to use the glob module.

> for i in allfiles:
>   print i
>   a.write(i)
>   a.write("\n")

The name "i" is normally used for integers, not file names. It would be 
better to write that as:

for filename in allfiles:
print filename
a.write(filename + '\n')



-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] WRITING XLS FROM OS.WALK()

2010-10-08 Thread David Hutto
On Fri, Oct 8, 2010 at 11:55 PM, Steven D'Aprano  wrote:
> On Sat, 9 Oct 2010 06:34:44 am Susana Iraiis Delgado Rodriguez wrote:
>> Hello members:
>> I developed a Python module to make a list which contains all the
>> files ending with .shp and .dbf extensions, I have solved this
>> already,
>
>
> I'm sorry to tell you that you've just reinvented the wheel. This was
> already solved, a long, long time ago. It is called the glob module:

Hey,  buddy pal. Isn't it true that newbs should take of advantage of
the fact that you have to solve the problem pythonically(as in by
yourself), even if the function already exists? If I get the gist of
thinikig like a programmer.

>
 import glob
 glob.glob("/home/steve/*.jpg")
> ['/home/steve/hoversonic.jpg', '/home/steve/seperated_at_birth.jpg']
 glob.glob("/home/steve/*.txt")
> ['/home/steve/woss.txt', '/home/steve/file.txt', '/home/steve/post.txt']
>
>
> You should use that. It works, it is tested and thoroughly debugged, and
> it is powerful.

Certainly so, but not as powerful as the individual's ingenuity in
solving the problem at hand without foreknowledge of the 'known'
solution.

>
>
>> but now I want to write an excel file from it. The file
>> should show the full path from the found files.
>
>
> Excel files are a proprietary, secret, binary file format. There is a
> Python project to allow reading and writing Excel files, but since it
> has to reverse-engineer the secret format, there's no guarantee that it
> will work. Having said that, I believe that it is very reliable, but
> I've never used it myself.
>
> Google on "python read write excel files" for more information.
>
> However, if your only aim is to make the data available to Excel, and
> you don't care what sort of file you use, the best way is the standard
> interchange format between spreadsheet applications, the comma-
> separated value file, or CSV. This is a plain-text file, and Python
> comes with a module for reading and writing them. From the interactive
> interpreter, run this for more information:
>
> import csv
> help(csv)
>
>
>
>> This is the code:
>>
>> import os
>> a = open ("directorio.xls","w")
>
> Just because you name a file .xls doesn't make it an actual Excel file,
> any more than taking a JPEG and renaming it "word.exe" would turn it
> into the Microsoft Word application.
>
>
>> allfiles = [] #store all files found
>>      for root,dir,files in os.walk("C:\\"):
>>            filelist = [ os.path.join(root,fi) for fi in files if
>> fi.endswith(".shp") or fi.endswith(".dbf") ]
>
>
> This isn't your actual code. I know this, because the indentation is
> broken and it gives a syntax error.
>
>>            for f in filelist:
>>                 allfiles.append(f)
>
> This is better written as:
>
> allfiles.extend(filelist)
>
>
> but of course it is better to use the glob module.
>
>> for i in allfiles:
>>       print i
>>       a.write(i)
>>       a.write("\n")
>
> The name "i" is normally used for integers, not file names. It would be
> better to write that as:
>
> for filename in allfiles:
>    print filename
>    a.write(filename + '\n')
>
>
>
> --
> Steven D'Aprano
> ___
> Tutor maillist  -  tu...@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

No problems here yet though buddy.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] WRITING XLS FROM OS.WALK()

2010-10-08 Thread Steven D'Aprano
On Sat, 9 Oct 2010 03:15:35 pm you wrote:

> > You should use that. It works, it is tested and thoroughly
> > debugged, and it is powerful.
>
> Certainly so, but not as powerful as the individual's ingenuity in
> solving the problem at hand without foreknowledge of the 'known'
> solution.

I suppose you made your own computer, smelting your own ores to get the 
metals and creating your own plastics from oil you dug up yourself, 
right? And then you wrote your own operating system, and wrote your own 
programming language which just happened to be exactly the same as 
Python in every possible way.

My uncle once went to the doctor complaining about general ill-health. 
The doctor sent him to a specialist, who examined him for five minutes, 
ran a blood sample through a little hand-held device, and two minutes 
later said "You've got such-and-such a disease. Here's my bill for 
$500."

My uncle got all indignant. "$500? You've hardly done anything! Why 
should you get so much just because you've got a tool that does the 
work for you?"

The specialist replied "The bill is $10 for my time, and $490 for 
knowing which was the right tool to use."


-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] WRITING XLS FROM OS.WALK()

2010-10-08 Thread David Hutto
On Sat, Oct 9, 2010 at 2:12 AM, Steven D'Aprano  wrote:
> On Sat, 9 Oct 2010 03:15:35 pm you wrote:
>
>> > You should use that. It works, it is tested and thoroughly
>> > debugged, and it is powerful.
>>
>> Certainly so, but not as powerful as the individual's ingenuity in
>> solving the problem at hand without foreknowledge of the 'known'
>> solution.
>
> I suppose you made your own computer, smelting your own ores to get the
> metals and creating your own plastics from oil you dug up yourself,

Sometimes breaking it down to bear  essentials is wht you need, and
sometimes, you need to
take advantage of the 'frosting' a language provides

> right? And then you wrote your own operating system, and wrote your own
> programming language which just happened to be exactly the same as
> Python in every possible way.

Not in every way. but  a way that makes sense to a demographic, just
the way python overwrites(wraps faster languages within it's compiled,
then .pyc's it to compiled), several other languages that are the same
or even more advocated to the new computer scientist.



>
> My uncle once went to the doctor complaining about general ill-health.
> The doctor sent him to a specialist, who examined him for five minutes,
> ran a blood sample through a little hand-held device, and two minutes
> later said "You've got such-and-such a disease. Here's my bill for
> $500."

Specialists always charge extra, and this is new how?

>
> My uncle got all indignant. "$500? You've hardly done anything! Why
> should you get so much just because you've got a tool that does the
> work for you?"
>
> The specialist replied "The bill is $10 for my time, and $490 for
> knowing which was the right tool to use."

A hammer can do the same in some instances, just the same as a pair of
wire cutters tapping the same nail in. Both get the job done, but
experience dictates the knowledge one uses for the fastest result, eg.
the price one is paid for the time they can do it in->project vs per
hour.

>
>
> --
> Steven D'Aprano
> ___
> Tutor maillist  -  tu...@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Interpolation

2010-10-08 Thread David Hutto
Maybe I missed it, even in the google searches/manuals, but does
someone know of an introduction to python interpolation that show the
different forms of %
, as in %s = string, and %d = digit(i think, or correct me).

TIA,
David
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] WRITING XLS FROM OS.WALK()

2010-10-08 Thread David Hutto
Here's a little 'anomaly' though, programmers say hammer when the
truth is, that modern construction should use pneumatic tools, as in
air hammer.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor