Re: [Tutor] Unusual pathfile

2011-09-13 Thread Susana Iraiis Delgado Rodriguez
=LEFT, padx=2, pady=2)
b = Button(toolbar, text=Escriba extension, width=15, command=extension)
b.pack(side=LEFT, padx=2, pady=2)
b = Button(toolbar, text=Nombre de csv, width=15, command=csv_w)
b.pack(side=LEFT, padx=2, pady=2)
b = Button(toolbar, text=Aceptar, width=6, command=buscar)
b.pack(side=LEFT, padx=2, pady=2)
toolbar.pack(side=TOP, fill=X)
root.mainloop()
2011/9/12 Alan Gauld alan.ga...@btinternet.com

 On 12/09/11 15:49, Susana Iraiis Delgado Rodriguez wrote:

 Hi!
 I developed a python gui module to make a walk through a directory. This
 time I want the user to select the parameters I need from the python
 gui. The results will be written in a csv file, the problem I found is
 the pathfile shows this way:
 C:/\Archivos de programa\FWTools2.4.7\bin\**mapnik-0.7.1\demo\data


 What exactly do you feel is wrong with that?
 Is it the fact that the first slash after the colon is forward facing?
 Or is there something else?


 I'm workin with Python 2.6.6 and Windows XP, the code is:


 Could you please use a few more spaces. Both to indent the code (2 spaces
 ids really the minimum and 3 or 4 is normal. But one is
 useless) and to separate the functions vertically. (ie a blank line before
 the def statements)

 It is really very hard work wading through this stuff! I don't know how you
 can read it but I'm struggling to see the structure.



 from Tkinter import * #Llamo las librerias graficas de Tk
 import tkSimpleDialog #Libreria de almacenamiento de dialogos
 import tkMessageBox #Libreria de mensajes
 import tkFileDialog
 import sys, os, csv, time, socket, stat
 from osgeo import ogr,gdal,osr
 from osgeo.gdalconst import *
 from PIL import Image
 dir = 
 extn = 
 csv_name = 


 def directorio():
  global dir
  print 'Seleccione directorio donde empezar'
  dirname =
 tkFileDialog.askdirectory(**parent=root,initialdir=/,**
 title='Selecciona
 la ruta a escanear')
  if len(dirname )  0:
   print You chose %s % dirname
  dir = dirname


 def extension():
  global extn
  print Escribe la extension que necesitas buscar
  ext=tkSimpleDialog.askstring('**Extension a buscar:','')
  print 'Buscando archivos: ',ext
  extn = ext


 def csv_w():
  global csv_name
  print Nombre del csv a crear
  inv=tkSimpleDialog.askstring('**Nombre de .csv:','')
  print 'Archivo de salidad: ',inv
  csv_name = inv


 def boton4():
  print 'Iniciando...'
  gdal.AllRegister()
  file_list = []
  folders = None
  for root, folders, files in os.walk(dir):
   file_list.extend(os.path.join(**root,fi) for fi in files if
 fi.endswith(extn))
  f = open(csv_name, 'wb')
  log = open ('log_errores.txt','w')
  writer = csv.writer(f)
  ruta = 'Ruta'
  archivo = 'archivo'
  x_min = 'x_min'
  x_max = 'x_max'
  y_min = 'y_min'
  y_max = 'y_max'
  geometria = 'geometria'
  num_elem = 'num_elem'
  prj = '.prj'
  proyeccion = 'proyeccion'
  fecha = 'fecha_modificacion'
  creacion = 'fecha_creacion'
  ultimo = 'ultimo_acceso'
  tamanio = 'tamanio_aprox'
  maq = 'maquina_host'
  usu = 'usuario'
  campos =
 [ruta,archivo,x_min,x_max,y_**min,y_max,geometria,num_elem,**
 prj,proyeccion,creacion,fecha,**ultimo,tamanio,maq,usu]
  writer.writerow(campos)
  for row, filepath in enumerate(file_list, start=1):
   directorio = os.path.dirname(filepath)
   filename = os.path.basename(filepath)
   shapeData = ogr.Open(filepath)
   shp = 'Error al abrir el archivo' +filepath
   if shapeData is None:
print shp
log.write(shp+\n)




 I don't want to get filepath order


 I don't understand what that means?

 --
 Alan G
 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/tutorhttp://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] Unusual pathfile

2011-09-13 Thread Susana Iraiis Delgado Rodriguez
I think I've received many complains for my questions and messages, I know
you're great programmers and this is for helping beginners or any level of
Python users. I tried to correct the code I sent the best I could, than you
for your time, I'll try to manage it myself.
2011/9/13 Steven D'Aprano st...@pearwood.info

 Susana Iraiis Delgado Rodriguez wrote:

 Hi!

 I just want to look the pathfile like this: C:\Python26 instead of
 C:/\Python26, I feel the loop repeats its walking with this pathfile
 structure. About the indention for the code, I tried my best to make it
 clear ande neat. But the mi e-mail editor it's mixing-up spaces.
 Here's again:


 Susana, you are showing too much code that is unrelated to your problem.
 Your problem is that your code gives the wrong result for the file name: you
 want C:\Python26 but get C:/\Python26.

 You should isolate the part of your code that produces the path names. We
 don't need the part that creates buttons, or writes CSV files, or prints
 messages to the user. As it stands now, I can't even tell which part of the
 code generates C:/\Python26, let alone how to fix it.

 You should have a small function, no more than ten or twenty lines, that
 handles the path names, and nothing else.



 --
 Steven

 __**_
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/**mailman/listinfo/tutorhttp://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] Unusual pathfile

2011-09-12 Thread Susana Iraiis Delgado Rodriguez
Hi!
I developed a python gui module to make a walk through a directory. This
time I want the user to select the parameters I need from the python gui.
The results will be written in a csv file, the problem I found is the
pathfile shows this way:
C:/\Archivos de programa\FWTools2.4.7\bin\mapnik-0.7.1\demo\data
I'm workin with Python 2.6.6 and Windows XP, the code is:
from Tkinter import * #Llamo las librerias graficas de Tk
import tkSimpleDialog #Libreria de almacenamiento de dialogos
import tkMessageBox #Libreria de mensajes
import tkFileDialog
import sys, os, csv, time, socket, stat
from osgeo import ogr,gdal,osr
from osgeo.gdalconst import *
from PIL import Image
dir = 
extn = 
csv_name = 
def directorio():
 global dir
 print 'Seleccione directorio donde empezar'
 dirname =
tkFileDialog.askdirectory(parent=root,initialdir=/,title='Selecciona la
ruta a escanear')
 if len(dirname )  0:
  print You chose %s % dirname
 dir = dirname
def extension():
 global extn
 print Escribe la extension que necesitas buscar
 ext=tkSimpleDialog.askstring('Extension a buscar:','')
 print 'Buscando archivos: ',ext
 extn = ext
def csv_w():
 global csv_name
 print Nombre del csv a crear
 inv=tkSimpleDialog.askstring('Nombre de .csv:','')
 print 'Archivo de salidad: ',inv
 csv_name = inv
def boton4():
 print 'Iniciando...'
 gdal.AllRegister()
 file_list = []
 folders = None
 for root, folders, files in os.walk(dir):
  file_list.extend(os.path.join(root,fi) for fi in files if
fi.endswith(extn))
 f = open(csv_name, 'wb')
 log = open ('log_errores.txt','w')
 writer = csv.writer(f)
 ruta = 'Ruta'
 archivo = 'archivo'
 x_min = 'x_min'
 x_max = 'x_max'
 y_min = 'y_min'
 y_max = 'y_max'
 geometria = 'geometria'
 num_elem = 'num_elem'
 prj = '.prj'
 proyeccion = 'proyeccion'
 fecha = 'fecha_modificacion'
 creacion = 'fecha_creacion'
 ultimo = 'ultimo_acceso'
 tamanio = 'tamanio_aprox'
 maq = 'maquina_host'
 usu = 'usuario'
 campos =
[ruta,archivo,x_min,x_max,y_min,y_max,geometria,num_elem,prj,proyeccion,creacion,fecha,ultimo,tamanio,maq,usu]
 writer.writerow(campos)
 for row, filepath in enumerate(file_list, start=1):
  directorio = os.path.dirname(filepath)
  filename = os.path.basename(filepath)
  shapeData = ogr.Open(filepath)
  shp = 'Error al abrir el archivo' +filepath
  if shapeData is None:
   print shp
   log.write(shp+\n)
I don't want to get filepath order
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] 'function' object has no attribute 'writer'

2011-09-06 Thread Susana Iraiis Delgado Rodriguez
Hello Petter!!
Thank you for answer to my question. I apologize for the writing of my code,
won't happen again. I added the lines you suggested me, and the script work
fine. Than you!! Here's the code corrected and indented.

from Tkinter import * #Llamo las librerias graficas de Tk
import tkSimpleDialog #Libreria de almacenamiento de dialogos
import tkMessageBox #Libreria de mensajes
import tkFileDialog
import sys, os, csv, time, socket, stat
from osgeo import ogr,gdal,osr
from osgeo.gdalconst import *
from PIL import Image
dir = 
extn = 
csv_name = 
filesystemencoding = sys.getfilesystemencoding()

def directorio():
global dir
print 'Seleccione directorio donde empezar'
dirname =
tkFileDialog.askdirectory(parent=root,initialdir=/,title='Selecciona la
ruta a escanear')
if len(dirname )  0:
  print You chose %s % dirname
dir = dirname
def extension():
global extn
print Escribe la extension que necesitas buscar
ext=tkSimpleDialog.askstring('Extension a buscar:','')
print 'Buscando archivos: ',ext
extn = ext
def csv_w():
global csv_name
print Nombre del csv a crear
inv=tkSimpleDialog.askstring('Nombre de .csv:','')
print 'Archivo de salidad: ',inv
csv_name = inv
def boton4():
print 'Iniciando...'
gdal.AllRegister()
file_list = []
folders = None
for root, folders, files in os.walk(dir):
   file_list.extend(os.path.join(root,fi) for fi in files if
fi.endswith(extn))
f = open(csv_name, 'wb')
log = open ('log_errores.txt','w')
writer = csv.writer(f)
ruta = 'Ruta'
archivo = 'archivo'
x_min = 'x_min'
x_max = 'x_max'
y_min = 'y_min'
y_max = 'y_max'
geometria = 'geometria'
num_elem = 'num_elem'
prj = '.prj'
proyeccion = 'proyeccion'
fecha = 'fecha_modificacion'
creacion = 'fecha_creacion'
ultimo = 'ultimo_acceso'
tamanio = 'tamanio_aprox'
maq = 'maquina_host'
usu = 'usuario'
campos =
[ruta,archivo,x_min,x_max,y_min,y_max,geometria,num_elem,prj,proyeccion,creacion,fecha,ultimo,tamanio,maq,usu]
writer.writerow(campos)
for row, filepath in enumerate(file_list, start=1):
  directorio = os.path.dirname(filepath)
  filename = os.path.basename(filepath)
  shapeData = ogr.Open(filepath.encode(filesystemencoding))
 shp = 'Error al abrir el archivo' +filepath
..

2011/9/5 Peter Otten __pete...@web.de

 Susana Iraiis Delgado Rodriguez wrote:

 Susana, please use 4-space indents for your code samples. I've said it
 before, but I think it's worthwhile repeating because it makes it much
 easier to grasp the structure of a script at first sight.

  But now I get a differente error, this script is going to collect
  information from shapefiles, I asked the user where to start the search,
  the file extension, and the csv name. Now I get:
  import win
  Seleccione directorio donde empezar
  You chose C:/
  Escribe la extension que necesitas buscar
  Buscando archivos:  .shp
  Nombre del csv a crear
  Archivo de salidad:  gui.csv
  Iniciando...
  Exception in Tkinter callback
  Traceback (most recent call last):
File C:\Python26\lib\lib-tk\Tkinter.py, line 1410, in __call__
  return self.func(*args)
File win.py, line 65, in boton4
  shapeData = ogr.Open(filepath)
File C:\Python26\lib\site-packages\osgeo\ogr.py, line 4033, in Open
  return _ogr.Open(*args, **kwargs)
  TypeError: in method 'Open', argument 1 of type 'char const *'
 
  The other part of the code is:

  from osgeo import ogr,gdal,osr

shapeData = ogr.Open(filepath)

 filepath is a unicode string, your library seems to expect byte strings.
 Try converting it like so:

 import sys
 filesystemencoding = sys.getfilesystemencoding()
 #...
 shapeData = ogr.Open(filepath.encode(filesystemencoding))

 ___
 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] Getting values from different functions (def's)

2011-09-05 Thread Susana Iraiis Delgado Rodriguez
Hello Alan!!
It is exactly what I need to complete my task :D
Than you so much
2011/8/31 Alan Gauld alan.ga...@btinternet.com

 On 31/08/11 18:17, Susana Iraiis Delgado Rodriguez wrote:

 Hello list !!
 I'm developing a Python GUI application. I alreday developed a very
 simple window with buttons, each button will do a different task, but
 the most important button will need to get information gotten in
 previous python's functions. Let's say I have four functions but at the
 end I want to collet all the information gotten.


 Instead of (or as well as) printing the data you will need to store it in
 variables. Then you can use those variables in the other function.



 from Tkinter import *
 import tkSimpleDialog
 import tkMessageBox
 import tkFileDialog


 # define storage variables
 dir = 
 extn = 
 csv_name = 

 def directorio():

global dir# need to specify the global one


  print 'Seleccione directorio donde empezar'
  dirname =  tkFileDialog.askdirectory(**parent=root,

   initialdir=/,
   title='Selecciona  la ruta a escanear')

  if len(dirname )  0:
   print You chose %s % dirname


 dir = dirname  # store the value

 def extension():

global extn

  print Escribe la extension que necesitas buscar
  ext=tkSimpleDialog.askstring('**Extension a buscar:','')
  print 'Buscando archivos: ',ext

extn = ext

 def csv():

global csv_name

  print Nombre del csv a crear
  inv=tkSimpleDialog.askstring('**Nombre de .csv:','')
  print 'Archivo de salida: ',inv

csv_name = inv


 def boton4():
 #In this button I want to make a bigger process, but I need the root
 selected and the two strings the user types.
  print csv.inv #Obviously this throws an error


print dir,csv_name,extn

 But course in a GUI you would normally not use print but instead populate
 the text field of a label or Text widget or some such
 device.


 --
 Alan G
 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/tutorhttp://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] 'function' object has no attribute 'writer'

2011-09-05 Thread Susana Iraiis Delgado Rodriguez
I want to write a csv file, but I need the final user to give me some values
to open and update the file. My code is:
from Tkinter import * #Llamo las librerias graficas de Tk
import tkSimpleDialog #Libreria de almacenamiento de dialogos
import tkMessageBox #Libreria de mensajes
import tkFileDialog
import sys, os, csv, time, socket, stat
from osgeo import ogr,gdal,osr
from osgeo.gdalconst import *
from PIL import Image
dir = 
extn = 
csv_name = 
def directorio():
 global dir
 print 'Seleccione directorio donde empezar'
 dirname =
tkFileDialog.askdirectory(parent=root,initialdir=/,title='Selecciona la
ruta a escanear')
 if len(dirname )  0:
  print You chose %s % dirname
 dir = dirname
def extension():
 global extn
 print Escribe la extension que necesitas buscar
 ext=tkSimpleDialog.askstring('Extension a buscar:','')
 print 'Buscando archivos: ',ext
 extn = ext
def csv():
 global csv_name
 print Nombre del csv a crear
 inv=tkSimpleDialog.askstring('Nombre de .csv:','')
 print 'Archivo de salidad: ',inv
 csv_name = inv
def boton4():
 print 'Iniciando...'
 gdal.AllRegister()
 file_list = []
 folders = None
 for root, folders, files in os.walk(dir):
  file_list.extend(os.path.join(root,fi) for fi in files if
fi.endswith(extn))
 f = open(csv_name, 'wb')
 log = open ('log_errores.txt','w')
 writer = csv.writer(f)
... more code
But when I run it,console shows:
Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 b
win32
Type help, copyright, credits or license for more informa
 import win
 Seleccione directorio donde empezar
You chose C:/
Escribe la extension que necesitas buscar
Buscando archivos:  .shp
Nombre del csv a crear
Archivo de salidad:  gui.csv
Iniciando...
Exception in Tkinter callback
Traceback (most recent call last):
  File C:\Python26\lib\lib-tk\Tkinter.py, line 1410, in __call_
return self.func(*args)
  File win.py, line 43, in boton4
writer = csv.writer(open(csv_name, 'w'))
AttributeError: 'function' object has no attribute 'writer'
I read a tutorial and csv has a writer function, I'm lost
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] 'function' object has no attribute 'writer'

2011-09-05 Thread Susana Iraiis Delgado Rodriguez
Hello guys!!!
Shame on me, you're rigth I missunderstood the function and the module.
I change the name of my function and that part of my code worked.
But now I get a differente error, this script is going to collect
information from shapefiles, I asked the user where to start the search, the
file extension, and the csv name. Now I get:
 import win
 Seleccione directorio donde empezar
You chose C:/
Escribe la extension que necesitas buscar
Buscando archivos:  .shp
Nombre del csv a crear
Archivo de salidad:  gui.csv
Iniciando...
Exception in Tkinter callback
Traceback (most recent call last):
  File C:\Python26\lib\lib-tk\Tkinter.py, line 1410, in __call__
return self.func(*args)
  File win.py, line 65, in boton4
shapeData = ogr.Open(filepath)
  File C:\Python26\lib\site-packages\osgeo\ogr.py, line 4033, in Open
return _ogr.Open(*args, **kwargs)
TypeError: in method 'Open', argument 1 of type 'char const *'

The other part of the code is:
from Tkinter import * #Llamo las librerias graficas de Tk
import tkSimpleDialog #Libreria de almacenamiento de dialogos
import tkMessageBox #Libreria de mensajes
import tkFileDialog
import sys, os, csv, time, socket, stat
from osgeo import ogr,gdal,osr
from osgeo.gdalconst import *
from PIL import Image
dir = 
extn = 
csv_name = 

def directorio():
 global dir
 print 'Seleccione directorio donde empezar'
 dirname =
tkFileDialog.askdirectory(parent=root,initialdir=/,title='Selecciona la
ruta a escanear')
 if len(dirname )  0:
  print You chose %s % dirname
 dir = dirname
def extension():
 global extn
 print Escribe la extension que necesitas buscar
 ext=tkSimpleDialog.askstring('Extension a buscar:','')
 print 'Buscando archivos: ',ext
 extn = ext
def csv_w():
 global csv_name
 print Nombre del csv a crear
 inv=tkSimpleDialog.askstring('Nombre de .csv:','')
 print 'Archivo de salidad: ',inv
 csv_name = inv
def boton4():
 print 'Iniciando...'
 gdal.AllRegister()
 file_list = []
 folders = None
 for root, folders, files in os.walk(dir):
  file_list.extend(os.path.join(root,fi) for fi in files if
fi.endswith(extn))
 f = open(csv_name, 'wb')
 log = open ('log_errores.txt','w')
 writer = csv.writer(f)
 ruta = 'Ruta'
 archivo = 'archivo'
 x_min = 'x_min'
 x_max = 'x_max'
 y_min = 'y_min'
 y_max = 'y_max'
 geometria = 'geometria'
 num_elem = 'num_elem'
 prj = '.prj'
 proyeccion = 'proyeccion'
 fecha = 'fecha_modificacion'
 creacion = 'fecha_creacion'
 ultimo = 'ultimo_acceso'
 tamanio = 'tamanio_aprox'
 maq = 'maquina_host'
 usu = 'usuario'
 campos =
[ruta,archivo,x_min,x_max,y_min,y_max,geometria,num_elem,prj,proyeccion,creacion,fecha,ultimo,tamanio,maq,usu]
 writer.writerow(campos)
 for row, filepath in enumerate(file_list, start=1):
  directorio = os.path.dirname(filepath)
  filename = os.path.basename(filepath)
  shapeData = ogr.Open(filepath)
  shp = 'Error al abrir el archivo' +filepath
  if shapeData is None:
   print shp
   log.write(shp+\n)
2011/9/5 James Reynolds eire1...@gmail.com



   On Mon, Sep 5, 2011 at 12:08 PM, Susana Iraiis Delgado Rodriguez 
 susana.delgad...@utzmg.edu.mx wrote:

   I want to write a csv file, but I need the final user to give me some
 values to open and update the file. My code is:
 from Tkinter import * #Llamo las librerias graficas de Tk
 import tkSimpleDialog #Libreria de almacenamiento de dialogos
 import tkMessageBox #Libreria de mensajes
 import tkFileDialog
 import sys, os, csv, time, socket, stat
 from osgeo import ogr,gdal,osr
 from osgeo.gdalconst import *
 from PIL import Image
 dir = 
 extn = 
 csv_name = 
 def directorio():
  global dir
  print 'Seleccione directorio donde empezar'
  dirname =
 tkFileDialog.askdirectory(parent=root,initialdir=/,title='Selecciona la
 ruta a escanear')
  if len(dirname )  0:
   print You chose %s % dirname
  dir = dirname
 def extension():
  global extn
  print Escribe la extension que necesitas buscar
  ext=tkSimpleDialog.askstring('Extension a buscar:','')
  print 'Buscando archivos: ',ext
  extn = ext
 def csv():
  global csv_name
  print Nombre del csv a crear
  inv=tkSimpleDialog.askstring('Nombre de .csv:','')
  print 'Archivo de salidad: ',inv
  csv_name = inv
 def boton4():
  print 'Iniciando...'
  gdal.AllRegister()
  file_list = []
  folders = None
  for root, folders, files in os.walk(dir):
   file_list.extend(os.path.join(root,fi) for fi in files if
 fi.endswith(extn))
  f = open(csv_name, 'wb')
  log = open ('log_errores.txt','w')
  writer = csv.writer(f)
 ... more code
 But when I run it,console shows:
 Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 b
 win32
 Type help, copyright, credits or license for more informa
  import win
  Seleccione directorio donde empezar
 You chose C:/
 Escribe la extension que necesitas buscar
 Buscando archivos:  .shp
 Nombre del csv a crear
 Archivo de salidad:  gui.csv
 Iniciando...
 Exception in Tkinter callback
 Traceback (most recent call last):
   File C:\Python26\lib\lib-tk\Tkinter.py, line 1410, in __call_

[Tutor] Getting values from different functions (def's)

2011-08-31 Thread Susana Iraiis Delgado Rodriguez
Hello list !!
I'm developing a Python GUI application. I alreday developed a very simple
window with buttons, each button will do a different task, but the most
important button will need to get information gotten in previous python's
functions. Let's say I have four functions but at the end I want to collet
all the information gotten.
from Tkinter import *
import tkSimpleDialog
import tkMessageBox
import tkFileDialog
def directorio():
 print 'Seleccione directorio donde empezar'
 dirname =
tkFileDialog.askdirectory(parent=root,initialdir=/,title='Selecciona la
ruta a escanear')
 if len(dirname )  0:
  print You chose %s % dirname
def extension():
 print Escribe la extension que necesitas buscar
 ext=tkSimpleDialog.askstring('Extension a buscar:','')
 print 'Buscando archivos: ',ext
def csv():
 print Nombre del csv a crear
 inv=tkSimpleDialog.askstring('Nombre de .csv:','')
 print 'Archivo de salida: ',inv
def boton4():
#In this button I want to make a bigger process, but I need the root
selected and the two strings the user types.
 print csv.inv #Obviously this throws an error
root = Tk()
top = Toplevel()
root.minsize(400,200)
toolbar = Frame(root)
b = Button(toolbar, text=Selecciona ruta, width=15, command=directorio)
b.pack(side=LEFT, padx=2, pady=2)
b = Button(toolbar, text=Escriba extension, width=15, command=extension)
b.pack(side=LEFT, padx=2, pady=2)
b = Button(toolbar, text=Nombre de csv, width=15, command=csv)
b.pack(side=LEFT, padx=2, pady=2)
b = Button(toolbar, text=Salir, width=6, command=boton4)
b.pack(side=LEFT, padx=2, pady=2)
toolbar.pack(side=TOP, fill=X)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Making a Python Window

2011-08-22 Thread Susana Iraiis Delgado Rodriguez
Hello List!!

I want to start desingning and developing python interfaces, but I don't
know what library or tool can help me to accomplish my goal. I have
installed the 2.6.6 python interpreter version, my operative system is
Windows XP. The interfaces I want to create will be very simple, just to
select a directory, entry some text, etc.
What will be the best option?
Thanks
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Making a Python Window

2011-08-22 Thread Susana Iraiis Delgado Rodriguez
Hello Alan!!

Thank you for tha advice! I'll look at your tutorial, and test the options
you're giving to me.
Thank you
2011/8/22 Alan Gauld alan.ga...@btinternet.com

 On 22/08/11 16:21, Susana Iraiis Delgado Rodriguez wrote:

  I want to start desingning and developing python interfaces, but I don't
 know what library or tool can help me to accomplish my goal.


 Three are pros and cons to all the different options available.

 My personal recommendation is to use Tkinter, purely because it comes with
 Python and is one of the easiest to learn.

 wxPython and PyQt and pyGTK are all valid alternatives but you need to
 download and install them. Tkinter comes in the standard library.


  Windows XP. The interfaces I want to create will be very simple, just to
 select a directory, entry some text, etc.


 You might find easyGUI is sufficient for your needs but its not a full GUI
 tool, it just makes using Python in a GUI environment slightly more user
 friendly.

 Personally I'd stick with Tkinter.

 You can find a short introduction to GUI programming in my tutorial, and it
 covers Tkinter and a short comparative example using wxPython.
 The latter is definitely a better bet if you want to move on to more
 sophisticated UIs, especially if you want to include features like printing
 (surprisingly difficult on Windows!)

 --
 Alan G
 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/tutorhttp://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] Message: pygobject_register_sinkfunc is deprecated (GtkWindow)

2011-08-17 Thread Susana Iraiis Delgado Rodriguez
Hello Timo!!

Thank you so much for your help! I'll do it
2011/8/17 Timo timomli...@gmail.com

 On 16-08-11 20:46, Susana Iraiis Delgado Rodriguez wrote:

 Hello List!

 I just started to use PyGTK and Glade to create graphical interfaces, my
 python interpreter version is 2.6.6; I also install the GTK2 Runtime
 enviroment and Glade 3.6.6. I also installed in my computer
 pycairo-1.8.10.win32-py2.6.**exe, pygobject-2.26.0-1.win32-py2.**6.exe
 and pygtk-2.16.0+glade.win32-py2.**6.exe so my graphic application will
 look and work fine.

 I tried to do an example in order to get familiar with this new tool, but
 when I run the script I got the next message:
 Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit
 (Intel)] on
 win32
 Type help, copyright, credits or license for more information.
  import glade1
 ** Message: pygobject_register_sinkfunc is deprecated (GtkWindow)
 ** Message: pygobject_register_sinkfunc is deprecated (GtkInvisible)
 ** Message: pygobject_register_sinkfunc is deprecated (GtkObject)
 
 My code is:
 import pygtk
 pygtk.require(2.0)
 import gtk
 import gtk.glade

 gtk.glade is deprecated, you should use the builtin gtk.builder instead
 (Google for examples). You should also get the latest GTK/PyGTK versions
 from the PyGTK website. There is a really nice all-in-one installer!

 Cheers,
 Timo


 class MainWin:
def __init__(self):
self.widgets = gtk.glade.XML(ejemplo_glade.**glade)
signals = { on_entry1_activate : self.on_button1_clicked,
on_button1_clicked : self.on_button1_clicked,
gtk_main_quit : gtk.main_quit }
self.widgets.signal_**autoconnect(signals)
self.label1 = self.widgets.get_widget(**label1)
self.entry1 = self.widgets.get_widget(**entry1)
def on_button1_clicked(self, widget):
texto = self.entry1.get_text()
self.label1.set_text(Hola %s % texto)


 if __name__ == __main__:
MainWin()
gtk.main()

 Does my python libraries are the correct ones for my interpreter?


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


 __**_
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/**mailman/listinfo/tutorhttp://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] Message: pygobject_register_sinkfunc is deprecated (GtkWindow)

2011-08-16 Thread Susana Iraiis Delgado Rodriguez
Hello List!

I just started to use PyGTK and Glade to create graphical interfaces, my
python interpreter version is 2.6.6; I also install the GTK2 Runtime
enviroment and Glade 3.6.6. I also installed in my computer
pycairo-1.8.10.win32-py2.6.exe, pygobject-2.26.0-1.win32-py2.6.exe and
pygtk-2.16.0+glade.win32-py2.6.exe so my graphic application will look and
work fine.

I tried to do an example in order to get familiar with this new tool, but
when I run the script I got the next message:
Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)]
on
win32
Type help, copyright, credits or license for more information.
 import glade1
** Message: pygobject_register_sinkfunc is deprecated (GtkWindow)
** Message: pygobject_register_sinkfunc is deprecated (GtkInvisible)
** Message: pygobject_register_sinkfunc is deprecated (GtkObject)

My code is:
import pygtk
pygtk.require(2.0)
import gtk
import gtk.glade

class MainWin:
def __init__(self):
self.widgets = gtk.glade.XML(ejemplo_glade.glade)
signals = { on_entry1_activate : self.on_button1_clicked,
on_button1_clicked : self.on_button1_clicked,
gtk_main_quit : gtk.main_quit }
self.widgets.signal_autoconnect(signals)
self.label1 = self.widgets.get_widget(label1)
self.entry1 = self.widgets.get_widget(entry1)
def on_button1_clicked(self, widget):
texto = self.entry1.get_text()
self.label1.set_text(Hola %s % texto)


if __name__ == __main__:
MainWin()
gtk.main()

Does my python libraries are the correct ones for my interpreter?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Python loop isn't working

2011-08-05 Thread Susana Iraiis Delgado Rodriguez
Hello list!
I have a python script which works with other libraries in order to create
maps. The script looks for an extension in a specific directory and with
mapnik makes the thumbnails.
The module works fine from Python command line and Pyton IDLE, but I need
this program to run from MS-DOS, when I added the try statement it started
to fail. Module runs but doesn't do what I need. Console shows:

C:\Python26shp2png.py C:\\ .png
Iniciando...
Listo

What am I doing wrong?

import mapnik
import os,fnmatch, sys
from mapnik import LineSymbolizer,PolygonSymbolizer,PointSymbolizer
from osgeo import ogr,gdal,osr

directorio = sys.argv[1]
extension = sys.argv[2]
try:
if len(sys.argv) == 3:
print 'Iniciando...'
file_list = []
folders = None
for root, folders, files in os.walk( directorio+'\\' ):
for filename in fnmatch.filter(files, extension):
file_list.append(os.path.join(root, filename))
for row, filepath in enumerate(file_list, start=1):
dir(LineSymbolizer().stroke)
shapeData = ogr.Open(filepath)
shp = 'Error al abrir el archivo' +filepath
if shapeData is None:
print shp
continue
layer = shapeData.GetLayer()
defn = layer.GetLayerDefn()
geo = defn.GetGeomType()
(ruta, filename) = os.path.split(filepath)
archivo = os.path.splitext(filename)
i = archivo[0]+'.png'

m = mapnik.Map(800,500,+proj=latlong +datum=WGS84)
m.background = mapnik.Color('#EBEBEB')
s = mapnik.Style()
r=mapnik.Rule()

if geo == 3 or geo == -2147483645:
print Trabajando mapa +ruta+\\+filename+ con geometria
+ str(geo)

r.symbols.append(mapnik.PolygonSymbolizer(mapnik.Color('#EB784B')))

r.symbols.append(mapnik.LineSymbolizer(mapnik.Color('rgb(170%,170%,170%)'),0.9))
s.rules.append(r)
m.append_style('My Style',s)
lyr = mapnik.Layer('world',+proj=latlong +datum=WGS84)
try:
lyr.datasource =
mapnik.Shapefile(base=ruta,file=archivo[0])
lyr.styles.append('My Style')
m.layers.append(lyr)
m.zoom_to_box(lyr.envelope())
mapnik.render_to_file(m,i, 'png')
print La imagen  +i+  fue creada.
except RuntimeError, e:
print 'Shapefile invalida'
continue

elif geo == 2 or geo == -2147483646:
print Trabajando mapa +ruta+\\+filename+ con geometria
+ str(geo)

r.symbols.append(mapnik.LineSymbolizer(mapnik.Color('#EB784B'),0.9))
s.rules.append(r)
m.append_style('My Style',s)
lyr = mapnik.Layer('world',+proj=latlong +datum=WGS84)
try:
lyr.datasource =
mapnik.Shapefile(base=ruta,file=archivo[0])
lyr.styles.append('My Style')
m.layers.append(lyr)
m.zoom_to_box(lyr.envelope())
mapnik.render_to_file(m,i, 'png')
print La imagen  +i+  fue creada.
except RuntimeError, e:
print 'Shapefile invalida'
continue

elif geo == 1 or geo == -2147483647:
print Trabajando mapa +ruta+\\+filename+ con geometria
+ str(geo)
blue =
mapnik.PointSymbolizer('C:\Python26\icono.png','png',50,50)
blue.allow_overlap = True
s=mapnik.Style()
r=mapnik.Rule()
r.symbols.append(blue)
s.rules.append(r)
m.append_style('My Style',s)
lyr = mapnik.Layer('world',+proj=latlong +datum=WGS84)
try:
lyr.datasource =
mapnik.Shapefile(base=ruta,file=archivo[0])
lyr.styles.append('My Style')
m.layers.append(lyr)
m.zoom_to_box(lyr.envelope())
mapnik.render_to_file(m,i, 'png')
print La imagen  +i+  fue creada.
except RuntimeError, e:
print 'Shapefile invalida'
continue
else:
print Algo fallo y no entro a ninguna de las geometrias
print Listo
else:
print Tus argumentos no son correctos
except IndexError:
print Tus argumentos no son correctos
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Sum files' size

2011-07-29 Thread Susana Iraiis Delgado Rodriguez
Thank you to all of you!

After I read your mails I started to modify my code, I applied Ramit
suggestion and got the result I wanted:

mport os
file_list = []
folders = None
for root, folders, files in os.walk('C:\\'):
file_list.extend(os.path.join(
root,fi) for fi in files if (fi.endswith.shp))
for row, filepath in enumerate(file_list, start=1):
n = os.path.splitext(filepath)
p = n[0]+'.prj'
shx = n[0]+'.shx'


#Function to get size in humam readable terms:
def sizeof_fmt(num):
 for x in ['bytes','KB','MB','GB','TB']:
  if num  1024.0:
   return %3.1f%s % (num, x)
  num /= 1024.0
s = os.path.getsize(filepath)
shx1 = os.path.getsize(shx)
p1 = s = os.path.getsize(p)
total = sizeof_fmt(s+shx1+p1)



2011/7/28 Prasad, Ramit ramit.pra...@jpmchase.com

 kb = sizeof_fmt(s)
 shx1 = os.path.getsize(shx)
 kb2 = sizeof_fmt(shx1)
  total = kb+kb2+kb3

 Instead only retrieve the formatted output at the end. That way you will
 not have to worry about converting back from strings, nor have to worry
 about adding number with different units (e.g. 10KB + 10MB).

 kb = s
 kb2 = os.path.getsize(shx)
 total = sizeof_fmt(kb+kb2+kb3)

 Ramit


 Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
 712 Main Street | Houston, TX 77002
 work phone: 713 - 216 - 5423



 This communication is for informational purposes only. It is not
 intended as an offer or solicitation for the purchase or sale of
 any financial instrument or as an official confirmation of any
 transaction. All market prices, data and other information are not
 warranted as to completeness or accuracy and are subject to change
 without notice. Any comments or statements made herein do not
 necessarily reflect those of JPMorgan Chase  Co., its subsidiaries
 and affiliates.

 This transmission may contain information that is privileged,
 confidential, legally privileged, and/or exempt from disclosure
 under applicable law. If you are not the intended recipient, you
 are hereby notified that any disclosure, copying, distribution, or
 use of the information contained herein (including any reliance
 thereon) is STRICTLY PROHIBITED. Although this transmission and any
 attachments are believed to be free of any virus or other defect
 that might affect any computer system into which it is received and
 opened, it is the responsibility of the recipient to ensure that it
 is virus free and no responsibility is accepted by JPMorgan Chase 
 Co., its subsidiaries and affiliates, as applicable, for any loss
 or damage arising in any way from its use. If you received this
 transmission in error, please immediately contact the sender and
 destroy the material in its entirety, whether in electronic or hard
 copy format. Thank you.

 Please refer to http://www.jpmorgan.com/pages/disclosures for
 disclosures relating to European legal entities.
 ___
 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] Sum files' size

2011-07-28 Thread Susana Iraiis Delgado Rodriguez
I want to get the size of  3 files. I already completed this step. Then I
need to sum the 3 results I got. In order to do it I have the next code:

import os
file_list = []
folders = None
for root, folders, files in os.walk('C:\\'):
file_list.extend(os.path.join(root,fi) for fi in files if
(fi.endswith.shp))
for row, filepath in enumerate(file_list, start=1):
n = os.path.splitext(filepath)
p = n[0]+'.prj'
shx = n[0]+'.shx'
s = os.path.getsize(filepath)

#Function to get size in humam readable terms:
def sizeof_fmt(num):
 for x in ['bytes','KB','MB','GB','TB']:
  if num  1024.0:
   return %3.1f%s % (num, x)
  num /= 1024.0

kb = sizeof_fmt(s)
shx1 = os.path.getsize(shx)
kb2 = sizeof_fmt(shx1)

#Finally I want to sum the 3 terms:
total = kb+kb2+kb3
But the output I got is : 15.5KB108.0bytes169.0bytes

Does anyone have an idea how to fix it?
Thank you!!
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Get file last user

2011-07-14 Thread Susana Iraiis Delgado Rodriguez
Thank you Alan for your answer!!

Well, I'm using Windows XP to run this script!!

So I guess there's nothing I can do, about it.

Than you

2011/7/12 Alan Gauld alan.ga...@btinternet.com

 Susana Iraiis Delgado Rodriguez wrote:

 Hello list!!!

 I want to get the last user who accessed to a file, ...

 Is there a way to find out who used the file for the last time?


 You don't say wgich OS you are using, which bis alklimportant.l Heavy duty
 industrial OS like OS.390,Pick and VAX VMS do record an audit trail, if the
 admin has switched that on. But mid range OS like Windows and Unix do not,
 so far as I know, record who made a change, just when the change was made.
 But that also probably depends on the filesystem in Linux, some of the more
 exotic ones may support audit trails.

 If you really need to know who made changes you need to use a version
 control system like RCS, CVS, SVN, etc. Thats what they are designed to do,
 amongst other things...

 HTH,

 Alan G.
 (From my Netbook because my PC broke! Boohoo... :-(


 __**_
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/**mailman/listinfo/tutorhttp://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] Get file last user

2011-07-13 Thread Susana Iraiis Delgado Rodriguez
Hello list!!!

I want to get the last user who accessed to a file, I already have the way
to know who owns the file, but I really need to get this information.
To get file user I'm using: os.environ.get(USERNAME) and to get the
machine host: socket.gethostname()
Is there a way to find out who used the file for the last time?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Break stament issue

2011-06-15 Thread Susana Iraiis Delgado Rodriguez
Hello members!!

Steven, I already changed the settings in the IDE to avoid the trouble when
I type the code.
In the other hand I added the pass statement so the script keep working even
though it finds an error, but the scripts ignore the pass statement. Console
prints:

Traceback (most recent call last):
  File stdin, line 1, in module
  File mapnik_punto_sin_duda.py, line 44, in module
lyr.datasource = mapnik.Shapefile(base=ruta,file=archivo[0])
  File C:\mapnik-0.7.1\python\2.6\site-packages\mapnik\__init__.py, line
282,
in Shapefile
return CreateDatasource(keywords)
RuntimeError: wrong file code : -1997790976

2011/6/14 James Reynolds eire1...@gmail.com



 On Tue, Jun 14, 2011 at 2:59 PM, Susana Iraiis Delgado Rodriguez 
 susana.delgad...@utzmg.edu.mx wrote:

 Hello members!

 I'm doing a script that needs to loop to get some information, in order to
 do that I'm using modules from OGR and Mapnik. These to get data from
 shapefiles, but some of the files have 0 elements, I wrote a line to
 validate it, but it hasn't worked, so I added a break to keep working. When
 I run the scipt I got the next error:
 Traceback (most recent call last):
   File pyshell#0, line 1, in module
 import mapnik_punto_sin_duda
   File C:\Python26\mapnik_punto_sin_duda.py, line 23
 break
^
 IndentationError: unexpected indent

 But I've read about this stamentet's use and I don't understand the reason
 I'm failing, the complete script is:
 import mapnik
 import os,fnmatch
 from mapnik import LineSymbolizer,PolygonSymbolizer,PointSymbolizer
 from osgeo import ogr,gdal,osr

 #Registra todos los drivers de GDAL
 file_list = []
 #Crear variable para buscar dentro de carpetas en el sistema
 folders = None
 #Se asigna el directorio raiz donde se van buscar los archivos, se hace un
 recorrido en la raiz
 for root, folders, files in os.walk( c:\\ ):
 #Agregar a la lista los elementos que traiga os.path.join, los
 archivos que terminen en extension .shp
 for filename in fnmatch.filter(files, '*.shp'):
 file_list.append(os.path.join(root, filename))
 #Recorrer la lista que se creo
 for row, filepath in enumerate(file_list, start=1):
 #Dividir la ruta en dos: directorio y nombre de archivo
 dir(LineSymbolizer().stroke)
 shapeData = ogr.Open(filepath)
 shp = 'Error al abrir el archivo' +filepath
 if shapeData is None:
 print shp
 break
 else:
 layer = shapeData.GetLayer()
 defn = layer.GetLayerDefn()
 geo = defn.GetGeomType()
 (ruta, filename) = os.path.split(filepath)
 archivo = os.path.splitext(filename)
 i = archivo[0]+'.png'

 m = mapnik.Map(800,500,+proj=latlong +datum=WGS84)
 m.background = mapnik.Color('#EBEBEB')
 s = mapnik.Style()
 r=mapnik.Rule()

 if geo == 3:
 print Trabajando mapa +ruta+\\+filename+ con
 geometria + str(geo)

 r.symbols.append(mapnik.PolygonSymbolizer(mapnik.Color('#EB784B')))

 r.symbols.append(mapnik.LineSymbolizer(mapnik.Color('rgb(170%,170%,170%)'),0.9))
 s.rules.append(r)
 m.append_style('My Style',s)
 lyr = mapnik.Layer('world',+proj=latlong
 +datum=WGS84)
 lyr.datasource =
 mapnik.Shapefile(base=ruta,file=archivo[0])
 lyr.styles.append('My Style')
 m.layers.append(lyr)
 m.zoom_to_box(lyr.envelope())
 mapnik.render_to_file(m,i, 'png')
 print La imagen  +i+  fue creada.
 elif geo == 2:
 print Trabajando mapa +ruta+\\+filename+ con
 geometria + str(geo)

 r.symbols.append(mapnik.LineSymbolizer(mapnik.Color('#EB784B'),0.9))
 s.rules.append(r)
 m.append_style('My Style',s)
 lyr = mapnik.Layer('world',+proj=latlong
 +datum=WGS84)
 lyr.datasource =
 mapnik.Shapefile(base=ruta,file=archivo[0])
 lyr.styles.append('My Style')
 m.layers.append(lyr)
 m.zoom_to_box(lyr.envelope())
 mapnik.render_to_file(m,i, 'png')
 print La imagen  +i+  fue creada.
 elif geo == 1:
 print Trabajando mapa +ruta+\\+filename+ con
 geometria + str(geo)
 blue =
 mapnik.PointSymbolizer('C:\Python26\icono.png','png',50,50)
 blue.allow_overlap = True
 s=mapnik.Style()
 r=mapnik.Rule()
 r.symbols.append(blue)
 s.rules.append(r)
 #s.rules.append(blue

[Tutor] Break stament issue

2011-06-14 Thread Susana Iraiis Delgado Rodriguez
Hello members!

I'm doing a script that needs to loop to get some information, in order to
do that I'm using modules from OGR and Mapnik. These to get data from
shapefiles, but some of the files have 0 elements, I wrote a line to
validate it, but it hasn't worked, so I added a break to keep working. When
I run the scipt I got the next error:
Traceback (most recent call last):
  File pyshell#0, line 1, in module
import mapnik_punto_sin_duda
  File C:\Python26\mapnik_punto_sin_duda.py, line 23
break
   ^
IndentationError: unexpected indent

But I've read about this stamentet's use and I don't understand the reason
I'm failing, the complete script is:
import mapnik
import os,fnmatch
from mapnik import LineSymbolizer,PolygonSymbolizer,PointSymbolizer
from osgeo import ogr,gdal,osr

#Registra todos los drivers de GDAL
file_list = []
#Crear variable para buscar dentro de carpetas en el sistema
folders = None
#Se asigna el directorio raiz donde se van buscar los archivos, se hace un
recorrido en la raiz
for root, folders, files in os.walk( c:\\ ):
#Agregar a la lista los elementos que traiga os.path.join, los
archivos que terminen en extension .shp
for filename in fnmatch.filter(files, '*.shp'):
file_list.append(os.path.join(root, filename))
#Recorrer la lista que se creo
for row, filepath in enumerate(file_list, start=1):
#Dividir la ruta en dos: directorio y nombre de archivo
dir(LineSymbolizer().stroke)
shapeData = ogr.Open(filepath)
shp = 'Error al abrir el archivo' +filepath
if shapeData is None:
print shp
break
else:
layer = shapeData.GetLayer()
defn = layer.GetLayerDefn()
geo = defn.GetGeomType()
(ruta, filename) = os.path.split(filepath)
archivo = os.path.splitext(filename)
i = archivo[0]+'.png'

m = mapnik.Map(800,500,+proj=latlong +datum=WGS84)
m.background = mapnik.Color('#EBEBEB')
s = mapnik.Style()
r=mapnik.Rule()

if geo == 3:
print Trabajando mapa +ruta+\\+filename+ con
geometria + str(geo)

r.symbols.append(mapnik.PolygonSymbolizer(mapnik.Color('#EB784B')))

r.symbols.append(mapnik.LineSymbolizer(mapnik.Color('rgb(170%,170%,170%)'),0.9))
s.rules.append(r)
m.append_style('My Style',s)
lyr = mapnik.Layer('world',+proj=latlong
+datum=WGS84)
lyr.datasource =
mapnik.Shapefile(base=ruta,file=archivo[0])
lyr.styles.append('My Style')
m.layers.append(lyr)
m.zoom_to_box(lyr.envelope())
mapnik.render_to_file(m,i, 'png')
print La imagen  +i+  fue creada.
elif geo == 2:
print Trabajando mapa +ruta+\\+filename+ con
geometria + str(geo)

r.symbols.append(mapnik.LineSymbolizer(mapnik.Color('#EB784B'),0.9))
s.rules.append(r)
m.append_style('My Style',s)
lyr = mapnik.Layer('world',+proj=latlong
+datum=WGS84)
lyr.datasource =
mapnik.Shapefile(base=ruta,file=archivo[0])
lyr.styles.append('My Style')
m.layers.append(lyr)
m.zoom_to_box(lyr.envelope())
mapnik.render_to_file(m,i, 'png')
print La imagen  +i+  fue creada.
elif geo == 1:
print Trabajando mapa +ruta+\\+filename+ con
geometria + str(geo)
blue =
mapnik.PointSymbolizer('C:\Python26\icono.png','png',50,50)
blue.allow_overlap = True
s=mapnik.Style()
r=mapnik.Rule()
r.symbols.append(blue)
s.rules.append(r)
#s.rules.append(blue)
m.append_style('My Style',s)
lyr = mapnik.Layer('world',+proj=latlong
+datum=WGS84)
lyr.datasource =
mapnik.Shapefile(base=ruta,file=archivo[0])
lyr.styles.append('My Style')
m.layers.append(lyr)
m.zoom_to_box(lyr.envelope())
mapnik.render_to_file(m,i, 'png')
print La imagen  +i+  fue creada.
else:
print Algo fallo y no entro a ninguna de las
geometrias
print Listo
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: Break stament issue

2011-06-14 Thread Susana Iraiis Delgado Rodriguez
-- Forwarded message --
From: Susana Iraiis Delgado Rodriguez susana.delgad...@utzmg.edu.mx
Date: 2011/6/14
Subject: Break stament issue
To: tutor@python.org


Hello members!

I'm doing a script that needs to loop to get some information, in order to
do that I'm using modules from OGR and Mapnik. These to get data from
shapefiles, but some of the files have 0 elements, I wrote a line to
validate it, but it hasn't worked, so I added a break to keep working. When
I run the scipt I got the next error:
Traceback (most recent call last):
  File pyshell#0, line 1, in module
import mapnik_punto_sin_duda
  File C:\Python26\mapnik_punto_sin_duda.py, line 23
break
   ^
IndentationError: unexpected indent

But I've read about this stamentet's use and I don't understand the reason
I'm failing, the complete script is:
import mapnik
import os,fnmatch
from mapnik import LineSymbolizer,PolygonSymbolizer,PointSymbolizer
from osgeo import ogr,gdal,osr

#Registra todos los drivers de GDAL
file_list = []
#Crear variable para buscar dentro de carpetas en el sistema
folders = None
#Se asigna el directorio raiz donde se van buscar los archivos, se hace un
recorrido en la raiz
for root, folders, files in os.walk( c:\\ ):
#Agregar a la lista los elementos que traiga os.path.join, los
archivos que terminen en extension .shp
for filename in fnmatch.filter(files, '*.shp'):
file_list.append(os.path.join(root, filename))
#Recorrer la lista que se creo
for row, filepath in enumerate(file_list, start=1):
#Dividir la ruta en dos: directorio y nombre de archivo
dir(LineSymbolizer().stroke)
shapeData = ogr.Open(filepath)
shp = 'Error al abrir el archivo' +filepath
if shapeData is None:
print shp
break
else:
layer = shapeData.GetLayer()
defn = layer.GetLayerDefn()
geo = defn.GetGeomType()
(ruta, filename) = os.path.split(filepath)
archivo = os.path.splitext(filename)
i = archivo[0]+'.png'

m = mapnik.Map(800,500,+proj=latlong +datum=WGS84)
m.background = mapnik.Color('#EBEBEB')
s = mapnik.Style()
r=mapnik.Rule()

if geo == 3:
print Trabajando mapa +ruta+\\+filename+ con
geometria + str(geo)

r.symbols.append(mapnik.PolygonSymbolizer(mapnik.Color('#EB784B')))

r.symbols.append(mapnik.LineSymbolizer(mapnik.Color('rgb(170%,170%,170%)'),0.9))
s.rules.append(r)
m.append_style('My Style',s)
lyr = mapnik.Layer('world',+proj=latlong
+datum=WGS84)
lyr.datasource =
mapnik.Shapefile(base=ruta,file=archivo[0])
lyr.styles.append('My Style')
m.layers.append(lyr)
m.zoom_to_box(lyr.envelope())
mapnik.render_to_file(m,i, 'png')
print La imagen  +i+  fue creada.
elif geo == 2:
print Trabajando mapa +ruta+\\+filename+ con
geometria + str(geo)

r.symbols.append(mapnik.LineSymbolizer(mapnik.Color('#EB784B'),0.9))
s.rules.append(r)
m.append_style('My Style',s)
lyr = mapnik.Layer('world',+proj=latlong
+datum=WGS84)
lyr.datasource =
mapnik.Shapefile(base=ruta,file=archivo[0])
lyr.styles.append('My Style')
m.layers.append(lyr)
m.zoom_to_box(lyr.envelope())
mapnik.render_to_file(m,i, 'png')
print La imagen  +i+  fue creada.
elif geo == 1:
print Trabajando mapa +ruta+\\+filename+ con
geometria + str(geo)
blue =
mapnik.PointSymbolizer('C:\Python26\icono.png','png',50,50)
blue.allow_overlap = True
s=mapnik.Style()
r=mapnik.Rule()
r.symbols.append(blue)
s.rules.append(r)
#s.rules.append(blue)
m.append_style('My Style',s)
lyr = mapnik.Layer('world',+proj=latlong
+datum=WGS84)
lyr.datasource =
mapnik.Shapefile(base=ruta,file=archivo[0])
lyr.styles.append('My Style')
m.layers.append(lyr)
m.zoom_to_box(lyr.envelope())
mapnik.render_to_file(m,i, 'png')
print La imagen  +i+  fue creada.
else:
print Algo fallo y no entro a ninguna de las
geometrias
print Listo
___
Tutor maillist  -  Tutor@python.org
To unsubscribe

Re: [Tutor] RuntimeError: file does not exist

2011-05-19 Thread Susana Iraiis Delgado Rodriguez
Hello everyone!

Well, I tried this code in other computer and it worked just fine. I changed
the line:
lyr.datasource = mapnik.Shapefile(base=filepath, file=filepath)
for lyr.datasource = mapnik.Shapefile(base=ruta,file=archivo[0])
I also did hard coding to test my script:
lyr.datasource =
mapnik.Shapefile(file='C:\\Python26\\tapalpa_05_plani_line')
It also worked as well!!

But when I run the module in my computer it throws many errors, if I use
lyr.datasource = mapnik.Shapefile(base=ruta,file=archivo[0]), it shows
Python Runtime Error: wrong file code: -1991225785



2011/5/19 Brad Posthumus mcgo...@yahoo.com




 Susana Iraiis Delgado Rodriguez wrote:
 
  Hello Alan!!
  Can you please tell me, how to rebuild my path? I've tried it, but I
  didn't
  succed =(
 
 

 The doctest for the Shapefile function includes this line:

shp = Shapefile(base='/home/mapnik/data',file='world_borders')

 This tells you base is a path, and file is your shapefile.

 In your code below, you're using the full path of the shapefile for both
 parameters. Fortunately, your code already seems to provide both required
 inputs. Try changing this line:

 lyr.datasource = mapnik.Shapefile(base=filepath, file=filepath)

 ...to:

 lyr.datasource = mapnik.Shapefile(base=ruta, file=filename)

 ---
 Brad Posthumus

 --
 View this message in context:
 http://old.nabble.com/-Tutor--RuntimeError%3A-file-does-not-exist-tp31640074p31655637.html
 Sent from the Python - tutor mailing list archive at Nabble.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


Re: [Tutor] RuntimeError: file does not exist

2011-05-19 Thread Susana Iraiis Delgado Rodriguez
Hi Alan!!

After I read your e-mail, I remebered that I run the scripts in a different
way.
The script worked properly when I run it from Python IDLE, I don't have any
idea the reason why.


2011/5/19 Alan Gauld alan.ga...@btinternet.com


 Susana Iraiis Delgado Rodriguez susana.delgad...@utzmg.edu.mx wrote


  Well, I tried this code in other computer and it worked just fine.



 But when I run the module in my computer it throws many errors,


 So what is different between the computers?
 What are the respective OS versions and Python versions?

 How exactly are you running the code on each
 computer - double click in exporer, from IDLE,  from the command line?

 Its hard to tell what the problem is from your description.


  lyr.datasource = mapnik.Shapefile(base=ruta,file=archivo[0]), it shows
 Python Runtime Error: wrong file code: -1991225785


 But that looks odd, possibly a problem with the python script file itself?


 --
 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

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


Re: [Tutor] RuntimeError: file does not exist

2011-05-18 Thread Susana Iraiis Delgado Rodriguez
Hello Alan!!
Can you please tell me, how to rebuild my path? I've tried it, but I didn't
succed =(

2011/5/17 Alan Gauld alan.ga...@btinternet.com


 Susana Iraiis Delgado Rodriguez susana.delgad...@utzmg.edu.mx wrote


  message which tells me the file I want to work with
 doesn't exist, but it does.


 I don't believe you! :-)

  Traceback (most recent call last):...

lyr.datasource = mapnik.Shapefile(base=filepath, file=filepath)
return CreateDatasource(keywords)
 RuntimeError: C:\Ýndice.shp/C:\Ýndice does not exist


 That file name has two C: in it which I am pretty sure is
 an illegal path in Windows. Therfore the file cannot exist.

 You just need to build your path correctly I suspect.

 --
 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

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


[Tutor] RuntimeError: file does not exist

2011-05-17 Thread Susana Iraiis Delgado Rodriguez
Hello list!!

I'm using a python dll to create images out from shapefiles. I import a
python module and its functions, when I want to use this library, I get a
message which tells me the file I want to work with doesn't exist, but it
does. I'm running the script from Windows. This is the code:
import mapnik
import os,fnmatc
file_list = []
folders = None
for root, folders, files in os.walk( C:\\ ):
for filename in fnmatch.filter(files, '*.shp'):
file_list.append(os.path.join(root, filename))
for row, filepath in enumerate(file_list, start=1):
(ruta, filename) = os.path.split(filepath)
i = archivo[0]+'.png'
m = mapnik.Map(800,500,+proj=latlong +datum=WGS84)
m.background = mapnik.Color('#f2eff9')
s = mapnik.Style()
r=mapnik.Rule()
r.symbols.append(mapnik.PolygonSymbolizer(mapnik.Color('steelblue')))

r.symbols.append(mapnik.LineSymbolizer(mapnik.Color('rgb(50%,50%,50%)'),0.1))
s.rules.append(r)
m.append_style('My Style',s)
lyr = mapnik.Layer('world',+proj=latlong +datum=WGS84)
lyr.datasource = mapnik.Shapefile(base=filepath, file=filepath)
lyr.styles.append('My Style')
m.layers.append(lyr)
m.zoom_to_box(lyr.envelope())
mapnik.render_to_file(m,i, 'png')
print Listo
I get the next error:
Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)]
on
win32
Type help, copyright, credits or license for more information.
 import imagen_shp
Traceback (most recent call last):
  File stdin, line 1, in module
  File imagen_shp.py, line 32, in module
lyr.datasource = mapnik.Shapefile(base=filepath, file=filepath)
  File C:\mapnik-0.7.1\python\2.6\site-packages\mapnik\__init__.py, line
282,
in Shapefile
return CreateDatasource(keywords)
RuntimeError: C:\Ýndice.shp/C:\Ýndice does not exist

I also reviewed the line which causes the error, it's a script from the
mapnik library:
def Shapefile(**keywords):
Create a Shapefile Datasource.
Required keyword arguments:
  file -- path to shapefile without extension
Optional keyword arguments:
  base -- path prefix (default None)
  encoding -- file encoding (default 'utf-8')
 from mapnik import Shapefile, Layer
 shp = Shapefile(base='/home/mapnik/data',file='world_borders')
 lyr = Layer('Shapefile Layer')
 lyr.datasource = shp
  
keywords['type'] = 'shape'
return CreateDatasource(keywords)
Does anyone could help me?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] RuntimeError: file does not exist

2011-05-17 Thread Susana Iraiis Delgado Rodriguez
Hello Emile!

Well, I changed the values because if I assigned different values, anyways I
got the next error:
Traceback (most recent call last):
  File stdin, line 1, in module
  File imagen_shp.py, line 32, in module
lyr.datasource = mapnik.Shapefile(base=raiz, file=archivo[0])
  File C:\mapnik-0.7.1\python\2.6\site-packages\mapnik\__init__.py, line
282,
in Shapefile
return CreateDatasource(keywords)
RuntimeError: Ýndice does not exist

2011/5/17 Emile van Sebille em...@fenx.com

 On 5/17/2011 10:10 AM Susana Iraiis Delgado Rodriguez said...

  Hello list!!

 I'm using a python dll to create images out from shapefiles. I import a
 python module and its functions, when I want to use this library, I get
 a message which tells me the file I want to work with doesn't exist, but
 it does. I'm running the script from Windows. This is the code:
 import mapnik
 import os,fnmatc
 file_list = []
 folders = None
 for root, folders, files in os.walk( C:\\ ):
 for filename in fnmatch.filter(files, '*.shp'):
 file_list.append(os.path.join(root, filename))
 for row, filepath in enumerate(file_list, start=1):
 (ruta, filename) = os.path.split(filepath)
 i = archivo[0]+'.png'
 m = mapnik.Map(800,500,+proj=latlong +datum=WGS84)
 m.background = mapnik.Color('#f2eff9')
 s = mapnik.Style()
 r=mapnik.Rule()
 r.symbols.append(mapnik.PolygonSymbolizer(mapnik.Color('steelblue')))


 r.symbols.append(mapnik.LineSymbolizer(mapnik.Color('rgb(50%,50%,50%)'),0.1))
 s.rules.append(r)
 m.append_style('My Style',s)
 lyr = mapnik.Layer('world',+proj=latlong +datum=WGS84)
 lyr.datasource = mapnik.Shapefile(base=filepath, file=filepath)
 lyr.styles.append('My Style')
 m.layers.append(lyr)
 m.zoom_to_box(lyr.envelope())
 mapnik.render_to_file(m,i, 'png')
 print Listo
 I get the next error:
 Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit
 (Intel)] on
 win32
 Type help, copyright, credits or license for more information.
   import imagen_shp
 Traceback (most recent call last):
   File stdin, line 1, in module
   File imagen_shp.py, line 32, in module
 lyr.datasource = mapnik.Shapefile(base=filepath, file=filepath)



 Without having actually dug into this, should base and file have the same
 value?

 Emile


File C:\mapnik-0.7.1\python\2.6\site-packages\mapnik\__init__.py,
 line 282,
 in Shapefile
 return CreateDatasource(keywords)
 RuntimeError: C:\Ýndice.shp/C:\Ýndice does not exist
  
 I also reviewed the line which causes the error, it's a script from the
 mapnik library:
 def Shapefile(**keywords):
 Create a Shapefile Datasource.
 Required keyword arguments:
   file -- path to shapefile without extension
 Optional keyword arguments:
   base -- path prefix (default None)
   encoding -- file encoding (default 'utf-8')
   from mapnik import Shapefile, Layer
   shp = Shapefile(base='/home/mapnik/data',file='world_borders')
   lyr = Layer('Shapefile Layer')
   lyr.datasource = shp
 
 keywords['type'] = 'shape'
 return CreateDatasource(keywords)
 Does anyone could help me?



 ___
 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 maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] ImportError: Module use of python25.dll conflicts with this version of Python.

2011-05-12 Thread Susana Iraiis Delgado Rodriguez
Hello list!

I just started working with a dll fro geospatial data, it uses Python to
analyze data, this package is OSGeo4W; when I run the script and got the
next error:
 import mapnik
Traceback (most recent call last):
  File stdin, line 1, in module
  File C:\OSGeo4W\apps\Python25\lib\site-packages\mapnik\__init__.py, line
42,
 in module
from _mapnik import *
ImportError: Module use of python25.dll conflicts with this version of
Python.

I'm using Python 2.6
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Unpack requires a string argument of length 8

2011-05-06 Thread Susana Iraiis Delgado Rodriguez
Hello Marc and Jim!

First of all, thanks to both of you!

I already changed the code, I added the try statement and the script runned
without ponting to an error. But now, I have another problem, even though,
it doesn't show an error message and makes the txt files, the files don't
have any lines written.

Before I added the try/catch lines, it showed the error, made the files and
writted them. I really need those txt files.

What did I do wrong?

import os,fnmatch
from osgeo import ogr,gdal,osr
from dbf import *
gdal.AllRegister()
file_list = []
folders = None
for root, folders, files in os.walk( C:\\ ):
for filename in fnmatch.filter(files, '*.shp'):
file_list.append(os.path.join(root, filename))
for row, filepath in enumerate(file_list, start=1):
(ruta, filename) = os.path.split(filepath)
shapeData = ogr.Open(filepath)
if shapeData is None:
print 'Error al abrir el archivo' +filepath
else:
n = os.path.splitext(filepath)
f = os.path.splitext(filename)
b = f[0]+'_bd.txt'
d = n[0]+'.dbf'
if os.path.lexists(d):
filepath1 = C:\\Python26\\dbf\\
a = open (filepath1 +b,w+)
try:
Dbf(d,new=False, readOnly=True)
for fldName in dbf.fieldDefs:
a.write(fldName.name)
a.write( || )
a.write(fldName.typeCode)
a.write(\n)
dbf.close()
a.close()
print n
except:
print 'El archivo ' +filepath+ ' esta vacio'
else:
print El archivo  +n[0]+.shp  no tiene dbf
print Listo
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Unpack requires a string argument of length 8

2011-05-02 Thread Susana Iraiis Delgado Rodriguez
I'm working on getting information that comes from a dbf file (database),
this dbf file is related to another file in the system, a shapefile. My code
is trying to get all the dbf name records, but when the systen gets an empty
file, my code fails:
Traceback (most recent call last):
  File stdin, line 1, in module
  File get_dbf.py, line 32, in module
dbf = Dbf(d,new=False, readOnly=True)
  File C:\Python26\lib\site-packages\dbf.py, line 135, in __init_
self.header = self.HeaderClass.fromStream(self.stream)
  File C:\Python26\lib\site-packages\header.py, line 109, in from
(_cnt, _hdrLen, _recLen) = struct.unpack(I2H, _data[4:12])
struct.error: unpack requires a string argument of length 8

How can I fix it?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Run application from MS-DOS with sys.argv

2011-04-01 Thread Susana Iraiis Delgado Rodriguez
Hello!

I'm going to answer to the question I posted in this list.
After a search trouhg web and analize the code, I just had to add a
try/except statement. Now I get what I need. Here is the information:

directorio = sys.argv[1]
extension = sys.argv[2]
csv_salida = sys.argv[3]
#Here I add the line:
try:
 if len(sys.argv) == 4:
 
 
else:
print Tus argumentos no son correctos
and here:
except IndexError:
print Tus argumentos no son correctos





2011/3/29 Susana Iraiis Delgado Rodriguez susana.delgad...@utzmg.edu.mx

 Hello List:

 I developed a script to walk through a specific directory in my PC and
 look for files with the same extension (.shp). I want the user to enter from
 MS-DOS and write the the directory, file extension and csv filename.
 My script reads the arguments from Windows console, but when I opened the
 txt file and csv file I noticed that isn't walking through all the root I
 wrote in MS-DOS. This is my module:

 import os, csv, time, socket, sys
 from osgeo import ogr,gdal,osr
 #This should be the order for the arguments('csv_args.py [root]
 [file_extension] [csv filename]')
 #The user is typing python csv_args.py C:\ .shp csv.csv
 directorio = sys.argv[1]
 extension = sys.argv[2]
 csv_salida = sys.argv[3]
 if len(sys.argv) == 4:
 print 'Iniciando...'
 gdal.AllRegister()
 file_list = []
 folders = None
 for root, folders, files in os.walk(directorio):
 file_list.extend(os.path.join(root,fi) for fi in files if
 fi.endswith(extension))
 f = open(csv_salida, 'wb')
 log = open ('errores.txt','w')
 writer = csv.writer(f)
 ruta = 'Ruta'
 archivo = 'archivo'
 x_min = 'x_min'
 x_max = 'x_max'
 y_min = 'y_min'
 y_max = 'y_max'
 geometria = 'geometria'
 num_elem = 'num_elem'
 prj = '.prj'
 proyeccion = 'proyeccion'
 fecha = 'fecha_modificacion'
 maq = 'maquina_host'
 usu = 'usuario'
 campos =
 [ruta,archivo,x_min,x_max,y_min,y_max,geometria,num_elem,prj,proyeccion,fecha,maq,usu]
 writer.writerow(campos)
 for row, filepath in enumerate(file_list, start=1):
 (ruta, filename) = os.path.split(filepath)
 shapeData = ogr.Open(filepath)
 shp = 'Error al abrir el archivo' +filepath
 if shapeData is None:
 print shp
 log.write(shp+\n)
 else:
 layer = shapeData.GetLayer()
 feature = layer.GetNextFeature()
 x_y = layer.GetExtent()
 x1 = x_y[0]
 x2 = x_y[1]
 y1 = x_y[2]
 y2 = x_y[3]
 defn = layer.GetLayerDefn()
 geo = defn.GetGeomType()
 cuenta = layer.GetFeatureCount()
 proy = layer.GetSpatialRef()
 prjtext = ''+str(proy)+''
 n = os.path.splitext(filepath)
 p = n[0]+'.prj'
 shx = n[0]+'.shx'
 dbf = n[0]+'.dbf'
 filepath = ''+filepath+''
 filename = ''+filename+''
 t = time.strftime(%m/%d/%Y %I:%M:%S
 %p,time.localtime(os.path.getmtime(filepath)))
 modificacion = ''+t+''
 usuario = os.environ.get(USERNAME)
 user = ''+usuario+''
 host = socket.gethostname()
 maquina = ''+host+''
 if os.path.exists(shx):
 print 'El archivo ' +shx +' existe'
 else:
 og.write('No existe el archivo ' +shx+\n)
 if os.path.exists(dbf):
 print 'El archivo ' +dbf +' existe'
 else:
 log.write('No existe el archivo ' +dbf+\n)
 if os.path.exists(p):
 aRow= [ filepath, filename, x1, x2, y1, y2, geo, cuenta, 1,
 prjtext, modificacion, maquina, user]
 writer.writerow(aRow)
 else:
 aRow1= [ filepath, filename, x1, x2, y1, y2, geo, cuenta,
 0, prjtext, modificacion, maquina, user]
 writer.writerow(aRow1)
 log.close()
 f.close()
 print El archivo esta listo
 else:
 print Tus argumentos no son correctos


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


[Tutor] Run application from MS-DOS with sys.argv

2011-03-29 Thread Susana Iraiis Delgado Rodriguez
Hello List:

I developed a script to walk through a specific directory in my PC and look
for files with the same extension (.shp). I want the user to enter from
MS-DOS and write the the directory, file extension and csv filename.
My script reads the arguments from Windows console, but when I opened the
txt file and csv file I noticed that isn't walking through all the root I
wrote in MS-DOS. This is my module:

import os, csv, time, socket, sys
from osgeo import ogr,gdal,osr
#This should be the order for the arguments('csv_args.py [root]
[file_extension] [csv filename]')
#The user is typing python csv_args.py C:\ .shp csv.csv
directorio = sys.argv[1]
extension = sys.argv[2]
csv_salida = sys.argv[3]
if len(sys.argv) == 4:
print 'Iniciando...'
gdal.AllRegister()
file_list = []
folders = None
for root, folders, files in os.walk(directorio):
file_list.extend(os.path.join(root,fi) for fi in files if
fi.endswith(extension))
f = open(csv_salida, 'wb')
log = open ('errores.txt','w')
writer = csv.writer(f)
ruta = 'Ruta'
archivo = 'archivo'
x_min = 'x_min'
x_max = 'x_max'
y_min = 'y_min'
y_max = 'y_max'
geometria = 'geometria'
num_elem = 'num_elem'
prj = '.prj'
proyeccion = 'proyeccion'
fecha = 'fecha_modificacion'
maq = 'maquina_host'
usu = 'usuario'
campos =
[ruta,archivo,x_min,x_max,y_min,y_max,geometria,num_elem,prj,proyeccion,fecha,maq,usu]
writer.writerow(campos)
for row, filepath in enumerate(file_list, start=1):
(ruta, filename) = os.path.split(filepath)
shapeData = ogr.Open(filepath)
shp = 'Error al abrir el archivo' +filepath
if shapeData is None:
print shp
log.write(shp+\n)
else:
layer = shapeData.GetLayer()
feature = layer.GetNextFeature()
x_y = layer.GetExtent()
x1 = x_y[0]
x2 = x_y[1]
y1 = x_y[2]
y2 = x_y[3]
defn = layer.GetLayerDefn()
geo = defn.GetGeomType()
cuenta = layer.GetFeatureCount()
proy = layer.GetSpatialRef()
prjtext = ''+str(proy)+''
n = os.path.splitext(filepath)
p = n[0]+'.prj'
shx = n[0]+'.shx'
dbf = n[0]+'.dbf'
filepath = ''+filepath+''
filename = ''+filename+''
t = time.strftime(%m/%d/%Y %I:%M:%S
%p,time.localtime(os.path.getmtime(filepath)))
modificacion = ''+t+''
usuario = os.environ.get(USERNAME)
user = ''+usuario+''
host = socket.gethostname()
maquina = ''+host+''
if os.path.exists(shx):
print 'El archivo ' +shx +' existe'
else:
og.write('No existe el archivo ' +shx+\n)
if os.path.exists(dbf):
print 'El archivo ' +dbf +' existe'
else:
log.write('No existe el archivo ' +dbf+\n)
if os.path.exists(p):
aRow= [ filepath, filename, x1, x2, y1, y2, geo, cuenta, 1,
prjtext, modificacion, maquina, user]
writer.writerow(aRow)
else:
aRow1= [ filepath, filename, x1, x2, y1, y2, geo, cuenta, 0,
prjtext, modificacion, maquina, user]
writer.writerow(aRow1)
log.close()
f.close()
print El archivo esta listo
else:
print Tus argumentos no son correctos
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Write new line(enter) in txt

2011-03-28 Thread Susana Iraiis Delgado Rodriguez
Hello list!!

This is a very simple question!! I want to write some lines in a txt file,
but my output looks like this:
No existe el archivo C:\índice.dbfNo existe el archivo C:\índice_dwg.dbfNo
existe el archivo C:\índice_raster.dbf
I need it to look like this:
No existe el archivo C:\índice.dbf
No existe el archivo C:\índice_dwg.dbf
No existe el archivo C:\índice_raster.dbf

The code I wrote is:
log = open ('errors.txt','wb')
shp = 'Error al abrir el archivo' +filepath
log.write(shp+\n)
n = os.path.splitext(filepath)
p = n[0]+'.prj'
shx = n[0]+'.shx'
dbf = n[0]+'.dbf'
if os.path.exists(shx):
print 'El archivo ' +shx +' existe'
else:
log.write('No existe el archivo ' +shx+\n)
if os.path.exists(dbf):
print 'El archivo ' +dbf +' existe'
else:
log.write('No existe el archivo ' +dbf+\n)
log.close()
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Write new line(enter) in txt

2011-03-28 Thread Susana Iraiis Delgado Rodriguez
Ok Flyyn!
Thank you for answered my question. I think I didn't explain what I need.
The printing statement is used to print a message to  the Windows console,
then the other line written in the else statement is:
log.write('No existe el archivo ' +shx+\n)
This is the part I'm struggling with, I don't know how to add the new line
to the txt

2011/3/28 Flynn, Stephen (L  P - IT) steve.fl...@capita.co.uk

 You don't print a newline when you print each line of the file
 contents...


 print 'El archivo ' +shx +' existe'





 You need to add a newline:

 print 'El archivo ' +shx +' existe' + '\n'




 
 From: tutor-bounces+steve.flynn=capita.co...@python.org [mailto:
 tutor-bounces+steve.flynn=capita.co...@python.org] On Behalf Of Susana
 Iraiis Delgado Rodriguez
 Sent: Monday, March 28, 2011 4:12 PM
 To: tutor@python.org
 Subject: [Tutor] Write new line(enter) in txt

 Hello list!!

 This is a very simple question!! I want to write some lines in a txt file,
 but my output looks like this:
 No existe el archivo C:\índice.dbfNo existe el archivo C:\índice_dwg.dbfNo
 existe el archivo C:\índice_raster.dbf
 I need it to look like this:
 No existe el archivo C:\índice.dbf
 No existe el archivo C:\índice_dwg.dbf
 No existe el archivo C:\índice_raster.dbf

 The code I wrote is:
 log = open ('errors.txt','wb')
 shp = 'Error al abrir el archivo' +filepath
 log.write(shp+\n)
 n = os.path.splitext(filepath)
 p = n[0]+'.prj'
 shx = n[0]+'.shx'
 dbf = n[0]+'.dbf'
 if os.path.exists(shx):
 print 'El archivo ' +shx +' existe'
 else:
 log.write('No existe el archivo ' +shx+\n)
 if os.path.exists(dbf):
 print 'El archivo ' +dbf +' existe'
 else:
 log.write('No existe el archivo ' +dbf+\n)
 log.close()


 This email has been scanned for all viruses by the MessageLabs SkyScan
 service.

 This email and any attachment to it are confidential.  Unless you are the
 intended recipient, you may not use, copy or disclose either the message or
 any information contained in the message. If you are not the intended
 recipient, you should delete this email and notify the sender immediately.

 Any views or opinions expressed in this email are those of the sender only,
 unless otherwise stated.  All copyright in any Capita material in this email
 is reserved.

 All emails, incoming and outgoing, may be recorded by Capita and monitored
 for legitimate business purposes.

 Capita exclude all liability for any loss or damage arising or resulting
 from the receipt, use or transmission of this email to the fullest extent
 permitted by law.

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


Re: [Tutor] Tutor Digest, Vol 85, Issue 103

2011-03-28 Thread Susana Iraiis Delgado Rodriguez
Thank you to everyone!

I changed the txt mode for my system, from 'wb' to 'w' and finally I got
what I need.

Than you!
2011/3/28 tutor-requ...@python.org

 Send Tutor mailing list submissions to
tutor@python.org

 To subscribe or unsubscribe via the World Wide Web, visit
http://mail.python.org/mailman/listinfo/tutor
 or, via email, send a message with subject or body 'help' to
tutor-requ...@python.org

 You can reach the person managing the list at
tutor-ow...@python.org

 When replying, please edit your Subject line so it is more specific
 than Re: Contents of Tutor digest...


 Today's Topics:

   1. Re: Pygame install help (Wayne Werner)
   2. Re: Write new line(enter) in txt (Susana Iraiis Delgado Rodriguez)
   3. Re: Write new line(enter) in txt (Joel Goldstick)


 --

 Message: 1
 Date: Mon, 28 Mar 2011 10:27:25 -0500
 From: Wayne Werner waynejwer...@gmail.com
 To: Chuck duxc...@gmail.com
 Cc: tutor@python.org
 Subject: Re: [Tutor] Pygame install help
 Message-ID:
aanlktinacrdgdsj4zkozb_gov6nf1+i8t_dcaoxfa...@mail.gmail.com
 Content-Type: text/plain; charset=iso-8859-1

 On Sun, Mar 27, 2011 at 12:31 PM, Chuck duxc...@gmail.com wrote:

  Does anyone have familiarity with installing pygame? It seems simple and
  straight forward enough, then why do I get the following from IDLE? This
 is
  the 3.1 Windows pygame .msi install...
 
  Python 3.2 (r32:88445, Feb 20 2011, 21:29:02) [MSC v.1500 32 bit (Intel)]
  on win32
  Type copyright, credits or license() for more information.
   import pygame
  Traceback (most recent call last):
File pyshell#0, line 1, in module
  import pygame
File C:\Python32\lib\site-
  packages\pygame\__init__.py, line 95, in module
  from pygame.base import *
  ImportError: DLL load failed: The specified module could not be found.
  
 

 Pygame support for Python 3 is a bit spotty (AFAIK). It will probably be
 easier using an earlier version of Python when working with Pygame.

 HTH,
 Wayne
 -- next part --
 An HTML attachment was scrubbed...
 URL: 
 http://mail.python.org/pipermail/tutor/attachments/20110328/4d663213/attachment-0001.html
 

 --

 Message: 2
 Date: Mon, 28 Mar 2011 09:28:18 -0600
 From: Susana Iraiis Delgado Rodriguez susana.delgad...@utzmg.edu.mx
 To: Flynn, Stephen (L  P - IT) steve.fl...@capita.co.uk
 Cc: tutor@python.org
 Subject: Re: [Tutor] Write new line(enter) in txt
 Message-ID:
AANLkTim0MRcDbXYJA=etflkhs9n2s3to-vg_7wbfs...@mail.gmail.com
 Content-Type: text/plain; charset=iso-8859-1

 Ok Flyyn!
 Thank you for answered my question. I think I didn't explain what I need.
 The printing statement is used to print a message to  the Windows console,
 then the other line written in the else statement is:
 log.write('No existe el archivo ' +shx+\n)
 This is the part I'm struggling with, I don't know how to add the new
 line
 to the txt

 2011/3/28 Flynn, Stephen (L  P - IT) steve.fl...@capita.co.uk

  You don't print a newline when you print each line of the file
  contents...
 
 
  print 'El archivo ' +shx +' existe'
 
 
 
 
 
  You need to add a newline:
 
  print 'El archivo ' +shx +' existe' + '\n'
 
 
 
 
  
  From: tutor-bounces+steve.flynn=capita.co...@python.org [mailto:
  tutor-bounces+steve.flynn=capita.co...@python.org] On Behalf Of Susana
  Iraiis Delgado Rodriguez
  Sent: Monday, March 28, 2011 4:12 PM
  To: tutor@python.org
  Subject: [Tutor] Write new line(enter) in txt
 
  Hello list!!
 
  This is a very simple question!! I want to write some lines in a txt
 file,
  but my output looks like this:
  No existe el archivo C:\?ndice.dbfNo existe el archivo
 C:\?ndice_dwg.dbfNo
  existe el archivo C:\?ndice_raster.dbf
  I need it to look like this:
  No existe el archivo C:\?ndice.dbf
  No existe el archivo C:\?ndice_dwg.dbf
  No existe el archivo C:\?ndice_raster.dbf
 
  The code I wrote is:
  log = open ('errors.txt','wb')
  shp = 'Error al abrir el archivo' +filepath
  log.write(shp+\n)
  n = os.path.splitext(filepath)
  p = n[0]+'.prj'
  shx = n[0]+'.shx'
  dbf = n[0]+'.dbf'
  if os.path.exists(shx):
  print 'El archivo ' +shx +' existe'
  else:
  log.write('No existe el archivo ' +shx+\n)
  if os.path.exists(dbf):
  print 'El archivo ' +dbf +' existe'
  else:
  log.write('No existe el archivo ' +dbf+\n)
  log.close()
 
 
  This email has been scanned for all viruses by the MessageLabs SkyScan
  service.
 
  This email and any attachment to it are confidential.  Unless you are the
  intended recipient, you may not use, copy or disclose either the message
 or
  any information contained in the message. If you are not the intended
  recipient, you should delete this email and notify

[Tutor] Read arguments from command line

2011-03-28 Thread Susana Iraiis Delgado Rodriguez
Hello everyone!

I want to run a python script which reads arguments from command line. I
searched in web and the module sys.argv came up. But I don't understand how
it works. I need to know how to pass arguments from command line and make
the python script works from MS-DOS instead of run my program from the
python console.

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


[Tutor] if os.path.exists() or if not os.path.exists()?

2011-03-24 Thread Susana Iraiis Delgado Rodriguez
Hello everyone!

I'm doing a python script that walks through files in my PC. Basically I'm
searching files that end up with .shp, but these files must have extensions
with .shx and .dbf. I want to write a .txt document which tells the user if
a file doesn't exist in the directory. But I haven't been sucessful, I got
the txt with wrong data, it shows an existing file.

import os, csv, time, socket
from osgeo import ogr,gdal,osr
from dbf import *

gdal.AllRegister()
file_list = [
folders = Non
for root, folders, files in os.walk( C:\\ ):
file_list.extend(os.path.join(root,fi) for fi in files if
fi.endswith(.shp))
writer = csv.writer(open('csv_pruebita.csv', wb))
ruta = 'Ruta'
archivo = 'archivo'
prj = '.prj'
proyeccion = 'proyeccion'
campos = [ruta,archivo,prj,proyeccion]
writer.writerow(campos)
for row, filepath in enumerate(file_list, start=1):
(ruta, filename) = os.path.split(filepath)
shapeData = ogr.Open(filepath)
shp = 'Error al abrir el archivo' +filepat
log = open (errors.txt,w+)
if shapeData is None:
print shp
log.write(shp + \n)
else:
#I splitted the filepath because I need the same filepath but with different
extension
n = os.path.splitext(filepath)
p = n[0]+'.prj'
shx = n[0]+'.shx'
dbf = n[0]+'.dbf'
filepath = ''+filepath+''
filename = ''+filename+''
#This block is wrong, I think here is the problem
if os.path.exists(shx):
print 'El archivo ' +shx +' existe'
else:
log.write('No existe el archivo ' +shx + \n)
if os.path.exists(dbf):
print 'El archivo ' +dbf +' existe'
log.write('No existe el archivo ' +dbf + \n)
#This block works properly
if os.path.exists(p):
prj_text = open(p, 'r').read()
prjtext = ''+prj_text+''
aRow= [ filepath, filename, 1, prjtext]
writer.writerow(aRow)
else:
no_prj = 'Sin prj, no se puede determinar la proyeccion'
aRow1= [ filepath, filename, 0, no_prj]
writer.writerow(aRow1)
log.close()
print El archivo esta listo
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] if os.path.exists() or if not os.path.exists()?

2011-03-24 Thread Susana Iraiis Delgado Rodriguez
OK!! I see the problem now!
I also did a little change to the code,  I open the .txt before the for
stamentet. The script is working properly
gdal.AllRegister()
file_list = [
folders = Non
for root, folders, files in os.walk( C:\\ ):
   file_list.extend(os.path.join(
root,fi) for fi in files if
fi.endswith(.shp))
f = open('csv_pruebita.csv', 'wb')
log = open ('errors.txt','wb')
writer = csv.writer(f)
ruta = 'Ruta'
archivo = 'archivo'
prj = '.prj'
proyeccion = 'proyeccion'
campos = [ruta,archivo,prj,proyeccion]
writer.writerow(campos)

for row, filepath in enumerate(file_list, start=1):
#Partir la ruta del archivo en dos, ruta y nombre del archivo
(ruta, filename) = os.path.split(filepath)
#Escribir el nombre del archivo
shapeData = ogr.Open(filepath)
shp = 'Error al abrir el archivo' +filepath
#Abrir archivo de errores
if shapeData is None:
print shp
log.write(shp+\n)
#Obtener la capa del shape
else:
..
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] CSV to Excel

2011-03-16 Thread Susana Iraiis Delgado Rodriguez
Thank you for your help!

Once I read your comments I tried both corrections in my code, but none of
them we're sucessful.
Tim's idea kept the quotes at the moment I open the csv in Excel, quotues
appeared at the beggining and the end of the row for Excel.
Joel's idea wrote just tha variable name 'filepath' and ''filename'.
The corrections I made were:
import os, csv, time, socket
from osgeo import ogr,gdal,osr
from dbf import *
gdal.AllRegister()

file_list = []
folders = None
for root, folders, files in os.walk( C:\\ ):
 file_list.extend(os.path.join(root,fi) for fi in files if
fi.endswith(.shp))

ofile  = open('csv1.csv', wb)
writer = csv.writer(open('csv2.csv', wb))
ruta = 'Ruta'
archivo = 'archivo'
prj = '.prj'
campos = [ruta,archivo,prj]
writer.writerow(campos)
for row, filepath in enumerate(file_list, start=1):
(ruta, filename) = os.path.split(filepath)
n = os.path.splitext(filepath)
p = n[0]+'.prj'
filepath = ''+filepath+''
filename = ''+filename+''
if os.path.exists(p):
prj_text = open(p, 'r').read()
prjtext = ''+prj_text+''
aRow= [ filepath, filename, 1, ]
writer.writerow(aRow)
   else:
no_prj = 'Sin prj, no se puede determinar la proyeccion'
aRow1= [ filepath, filename,0]
writer.writerow(aRow1)
print El archivo esta listo



2011/3/11 Tim Golden m...@timgolden.me.uk

 On 11/03/2011 8:59 PM, Susana Iraiis Delgado Rodriguez wrote:

 Hello list!!

 I'm trying to write a CSV file to work it with Excel. My python script is
 working, the issue is: when I import the file from excel the data comes
 with
 quotes at the beginnig and ending of the row. I don't want to have these
 quotes. What is wrong with my code?


 Essentially, the work is being done twice.
 The .writerow method expects a list which it will
 convert into a quoted, comma-separated string. You're
 giving it a list whose one element is a quoted, comma-separated
 string.

 Just pass it a list instead:

 writer.writerow (['Ruta', 'Archivo', '.prj'])
 ...
 writer.writerow ([filepath, filename, 1])

 (BTW, my naive knowledge of Spanish suggests that you're confusing
 the two identical-sounding English words: root - raiz and
 route - ruta).

 TJG

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


[Tutor] CSV to Excel

2011-03-11 Thread Susana Iraiis Delgado Rodriguez
Hello list!!

I'm trying to write a CSV file to work it with Excel. My python script is
working, the issue is: when I import the file from excel the data comes with
quotes at the beginnig and ending of the row. I don't want to have these
quotes. What is wrong with my code?

import os, csv
from osgeo import ogr,gdal,osr
from dbf import *
gdal.AllRegister()
file_list = []
folders = None
for root, folders, files in os.walk( C:\\ ):
file_list.extend(os.path.join(root,fi) for fi in files if
fi.endswith(.shp))
writer = csv.writer(open('csv2.csv', wb))
campos = ['Ruta,Archivo,.prj']
writer.writerow(campos)
for row, filepath in enumerate(file_list, start=1):
(ruta, filename) = os.path.split(filepath)
n = os.path.splitext(filepath)
p = n[0]+'.prj'
if os.path.exists(p):
aRow = [+filepath+,+filename+,1]
writer.writerow(aRow)
else:
aRow1 = [+filepath+,+filename+,0]
writer.writerow(aRow1)
print El archivo esta listo
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] 'ascii' codec can't decode byte

2010-12-10 Thread Susana Iraiis Delgado Rodriguez
Hello members:

I need your help, I'm developing a python script to make an excel file...
I've been working in this for a long time. The module will write some data
from a .shp file. Unfortuanely that information has some characters
unrecorgnized by ascii. I tried to fix this adding an unicode sentence, but
it didn't work, the script is:
import os, time,fnmatch
from xlwt import Workbook
from osgeo import ogr,gdal,osr
from dbf import *
gdal.AllRegister()
file_list = []
folders = None
for root, folders, files in os.walk( R:\\ ):
for filename in fnmatch.filter(files, '*.shp'):
file_list.append(os.path.join(root, filename)
wrkbk = Workbook()
wksht = wrkbk.add_sheet('shp')
wksht.row(0).write(0,'ruta')
wksht.row(0).write(1,'archivo'
wksht.row(0).write(2,'prj')
wksht.row(0).write(3,'fecha_modificacion')
wksht.row(0).write(4,'maquina_host')
wksht.row(0).write(5,'usuario')
for row, filepath in enumerate(file_list, start=1):
wksht.row(row).write(0, unicode(filepath,errors='ignore'))
(ruta, filename) = os.path.split(filepath)
wksht.row(row).write(1, unicode(filename,errors='ignore'))
n = os.path.splitext(filepath)
p = n[0]+'.prj'
if os.path.exists(p):
   prj_text = open(p, 'r').read()
   unicode(prj_text,errors='ignore')
   wksht.row(row).write(2,prj_text)
 else:
   wksht.row(row).write(2, 'Sin prj, no se puede determinar la
proyeccion')

 wksht.row(row).write(4, unicode(socket.gethostname(),errors='ignore'))

  t = time.strftime(%m/%d/%Y %I:%M:%S
%p,time.localtime(os.path.getmtime(filepath)))
  wksht.row(row).write(3, unicode(t,errors='ignore'))
   wksht.row(row).write(5,unicode(os.environ.get(USERNAME),errors='ignore'))
wrkbk.save('C:\\Python26\\biblio\\biblio_shp.xls')

When I run it, I got the next error:
Warning 1: organizePolygons() received an unexpected geometry.
Either a polygon with interior rings, or a polygon with less than 4 points,
or a non-Polygon geometry.  Return arguments as a collection.
Warning 1: Geometry of polygon of fid 0 cannot be translated to Simple
Geometry.
 All polygons will be contained in a multipolygon.
El archivo R:\Regiones\BosquePrimavera\Redefinici¾n de ptos del ANP del B la
P\D
atos GPS\Meridian\polnuevonm.shp no tiene dbf
Traceback (most recent call last):
  File stdin, line 1, in module
  File crawler_shp.py, line 138, in module
wrkbk.save('C:\\Python26\\biblio\\biblio_shp.xls')
  File C:\Python26\lib\site-packages\xlwt\Workbook.py, line 634, in save
doc.save(filename, self.get_biff_data())
  File C:\Python26\lib\site-packages\xlwt\Workbook.py, line 609, in
get_biff_d
ata
shared_str_table   = self.__sst_rec()
  File C:\Python26\lib\site-packages\xlwt\Workbook.py, line 571, in
__sst_rec
return self.__sst.get_biff_record()
  File C:\Python26\lib\site-packages\xlwt\BIFFRecords.py, line 53, in
get_biff
_record
self._add_to_sst(s)
  File C:\Python26\lib\site-packages\xlwt\BIFFRecords.py, line 66, in
_add_to_
sst
u_str = upack2(s, self.encoding)
  File C:\Python26\lib\site-packages\xlwt\UnicodeUtils.py, line 50, in
upack2
us = unicode(s, encoding)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xf3 in position 9:
ordinal
not in range(128)

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


Re: [Tutor] Save file in a specific directory

2010-12-09 Thread Susana Iraiis Delgado Rodriguez
Thank you Jerry! The suggestion you told me make my code worked!




 dbf = Dbf(d,new=False, readOnly=True)



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


[Tutor] Save file in a specific directory

2010-12-07 Thread Susana Iraiis Delgado Rodriguez
I make a script to redirect a txt file from an external directory, but in
this directory I don't have permission to write, just to read data. So I
make this module:
import os, time,fnmatch
from xlwt import Workbook
from osgeo import ogr,gdal,osr
from dbf import *
gdal.AllRegister()
file_list = []
folders = None
for root, folders, files in os.walk( R:\\ ):
for filename in fnmatch.filter(files, '*.shp'):
file_list.append(os.path.join(root, filename))
wrkbk = Workbook()
wksht = wrkbk.add_sheet('shp')
wksht.row(0).write(0,'ruta')
wksht.row(0).write(1,'archivo')
wksht.row(0).write(2,'estructura bd')
for row, filepath in enumerate(file_list, start=1):
wksht.row(row).write(0, filepath)
(ruta, filename) = os.path.split(filepath)
 wksht.row(row).write(1, filename)
 f = os.path.splitext(filename)
 t = f[0]+'_bd.txt'
 d = n[0]+'.dbf'
 if os.path.lexists(d):
   filepath = C:\\Python26\\
   a = open (filepath +t,w+)
   dbf = Dbf(d,new=False)
   for fldName in dbf.fieldDefs:
a.write(fldName.name)
a.write( || )
a.write(fldName.typeCode)
a.write(\n)
   dbf.close()
   a.close()
wksht.row(row).write(2, t)
   else:
   print El archivo  +n[0]+.shp  no tiene dbf
   wksht.row(row).write(10, Sin bd)


wrkbk.save('C\\Python26\\biblio_shp.xls')
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Save file in a specific directory

2010-12-07 Thread Susana Iraiis Delgado Rodriguez
My other message was incomplete, it was a mistake: This is the correct one

2010/12/7 Susana Iraiis Delgado Rodriguez susana.delgad...@utzmg.edu.mx

 I make a script to redirect a txt file from an external directory, but in
 this directory I don't have permission to write, just to read data. So I
 make this module:
 import os, time,fnmatch
 from xlwt import Workbook
 from osgeo import ogr,gdal,osr
 from dbf import *
 gdal.AllRegister()
 file_list = []
 folders = None
 for root, folders, files in os.walk( R:\\ ):
 for filename in fnmatch.filter(files, '*.shp'):
 file_list.append(os.path.join(root, filename))
 wrkbk = Workbook()
 wksht = wrkbk.add_sheet('shp')
 wksht.row(0).write(0,'ruta')
 wksht.row(0).write(1,'archivo')
 wksht.row(0).write(2,'estructura bd')
 for row, filepath in enumerate(file_list, start=1):
 wksht.row(row).write(0, filepath)
 (ruta, filename) = os.path.split(filepath)
  wksht.row(row).write(1, filename)
  f = os.path.splitext(filename)
  t = f[0]+'_bd.txt'
  d = n[0]+'.dbf'
  if os.path.lexists(d):
filepath = C:\\Python26\\
a = open (filepath +t,w+)
dbf = Dbf(d,new=False)
for fldName in dbf.fieldDefs:
a.write(fldName.name)
a.write( || )
a.write(fldName.typeCode)
a.write(\n)
dbf.close()
a.close()
wksht.row(row).write(2, t)
   else:
   print El archivo  +n[0]+.shp  no tiene dbf
   wksht.row(row).write(10, Sin bd
 wrkbk.save('C:\\Python26\\biblio_shp.xls')

When I run the script I got the next error:
 import crawler_shp
Traceback (most recent call last):
  File stdin, line 1, in module
  File crawler_shp.py, line 105, in module
dbf = Dbf(d,new=False)
  File C:\Python26\lib\site-packages\dbf.py, line 125, in __init__
self.stream = file(f, (r+b, rb)[bool(readOnly)])
IOError: [Errno 13] Permission denied: 'R:\\Aplicaciones\\IRISv3\\mis
proyectos\
\HURACAN\\BUFFER1000.dbf'

The error is pointing to a library I used to make the script run: dbf.py. in
thid lines:
if isinstance(f, basestring):
# a filename
self.name = f
if new:
# new table (table file must be
# created or opened and truncated)
self.stream = file(f, w+b)
else:
# tabe file must exist
self.stream = file(f, (r+b, rb)[bool(readOnly)])




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


[Tutor] SAVE FILE IN A SPECIFIC DIRECTORY

2010-12-06 Thread Susana Iraiis Delgado Rodriguez
I'm trying to save files into a specific directory, the file will be
generated from a python script. The script will look for some data stored in
a directory which only allows to read files, it doesn't let the user write
or modify information. But when I run the script I got the next error:
Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)]
on
win32
Type help, copyright, credits or license for more information.
 import crawler_shp
Traceback (most recent call last):
  File stdin, line 1, in module
  File crawler_shp.py, line 103, in module
a = open (filepath +t,w+)
IOError: [Errno 2] No such file or directory:
'C\\Python26\\BUFFER1000_bd.txt'

My script is:
import os, time, socket, pylab,fnmatch
from xlwt import Workbook
from osgeo import ogr,gdal,osr
from dbf import *

gdal.AllRegister()
file_list = []
folders = None
for root, folders, files in os.walk( R:\\ ):
 for filename in fnmatch.filter(files, '*.shp'):
  file_list.append(os.path.join(root, filename))
wrkbk = Workbook()
wksht = wrkbk.add_sheet('shp')
wksht.row(0).write(0,'ruta')
wksht.row(0).write(1,'archivo')
wksht.row(0).write(2,'estructura bd')
for row, filepath in enumerate(file_list, start=1):
 wksht.row(row).write(0, filepath)
 (ruta, filename) = os.path.split(filepath)
 wksht.row(row).write(1, filename)
  f = os.path.splitext(filename)
  t = f[0]+'_bd.txt'
  d = n[0]+'.dbf'
  if os.path.lexists(d):
  filepath = C\\Python26\\
   a = open (filepath +t,w+)
   dbf = Dbf(d,new=False)


   for fldName in dbf.fieldDefs:
a.write(fldName.name)
a.write( || )
a.write(fldName.typeCode)
a.write(\n)
   dbf.close()
   a.close()
wksht.row(row).write(2, t)
   else:
   print El archivo  +n[0]+.shp  no tiene dbf
   wksht.row(row).write(10, Sin bd)


wrkbk.save('C\\Python26\\biblio_shp.xls')
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] If os.path.lexists() isn't working properly

2010-11-26 Thread Susana Iraiis Delgado Rodriguez
Hello! After all the sugestions I received throught this list; I tried them
all and worked ok. At he end I noticed that a single variable change will
bring me the results I was looking for. In my code I replaced the line

n = os.path.splitext(filename)

for:
n = os.path.splitext(filepath)
 p = n[0]+'.prj'
 if os.path.exists(p):
... code

I just wanted to pointed out, thank you all of you!
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] If os.path.lexists() isn't working properly

2010-11-25 Thread Susana Iraiis Delgado Rodriguez
Hi Dave!

Thank you for your suggestion I haven't prevent the problems you're
describing, but I'm newbie in this stuff so, where should I repalce the
code?

Thank you again!
2010/11/24 Dave Angel da...@ieee.org

 On 01/-10/-28163 02:59 PM, Susana Iraiis Delgado Rodriguez wrote:

 Hello Peter!

 I added the line you suggested me and found out that I was just searching
 for the filenames without pointing to a specific directory, so Python took
 its directory (Python26) as default. After that I need to add a '\' to
 separate the path from the filename because it was reading them as a
 single
 string. But finally it worked nicely! here is the corrected script.

 snip

  wksht.row(row).write(1, filename)
  n = os.path.splitext(filename)
  p = ruta+'\\'+n[0]+'.prj'


 Use os.path.join() to combine these nodes.  If you use an explicit
 backslash you can trigger two problems:  1) Your code won't be portable to
 other platforms  2) You could have trouble if one of the components already
 has a path separator.


 DaveA

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


[Tutor] If os.path.lexists() isn't working properly

2010-11-24 Thread Susana Iraiis Delgado Rodriguez
Hello memebers:

I'm writing a python script to validate if files with extension .prj exist,
if they exist it should write 1 or 0 into an excel cell. I've working to do
this properly, but I'm not getting the results I need. The script doesn't
find all the files, is like the files don't exist but they exist, besides I
think is just reading some of the files that are in C:\Python 26. I really
need a hand on this.

import os, time, socket, pylab
from xlwt import Workbook
from osgeo import ogr,gdal,osr
from dbf import *
#Register GAL drivers
gdal.AllRegister()
#Create an empty list
file_list = []
folders = None
#Code to indicate directory
for root, folders, files in os.walk( C:\\ ):
 file_list.extend(os.path.join(root,fi) for fi in files if
fi.endswith(.shp))
#Open excel book
wrkbk = Workbook()
#Add excel sheet
wksht = wrkbk.add_sheet('shp')
wksht.row(0).write(0,'ruta')
wksht.row(0).write(1,'archivo')
wksht.row(0).write(2,'prj')
for row, filepath in enumerate(file_list, start=1):
wksht.row(row).write(0, filepath)
(ruta, filename) = os.path.split(filepath)
 wksht.row(row).write(1, filename)
 n = os.path.splitext(filename)
 p = n[0]+'.prj'
 if os.path.lexists(p):
  wksht.row(row).write(2, 1)
 else:
  wksht.row(row).write(2, 0)
wrkbk.save('shp3.xls')
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] If os.path.lexists() isn't working properly

2010-11-24 Thread Susana Iraiis Delgado Rodriguez
Hello Peter!

I added the line you suggested me and found out that I was just searching
for the filenames without pointing to a specific directory, so Python took
its directory (Python26) as default. After that I need to add a '\' to
separate the path from the filename because it was reading them as a single
string. But finally it worked nicely! here is the corrected script.

import os, time, socket, pylab, fnmatch
from xlwt import Workbook
from osgeo import ogr,gdal,osr
from dbf import *

gdal.AllRegister()
file_list = []
folders = None
for root, folders, files in os.walk( C:\\ ):
 for filename in fnmatch.filter(files, '*.shp'):
   file_list.append(os.path.join(root, filename))
wrkbk = Workbook()
wksht = wrkbk.add_sheet('shp')
wksht.row(0).write(0,'ruta')
wksht.row(0).write(1,'archivo')
wksht.row(0).write(2,'prj')
for row, filepath in enumerate(file_list, start=1):
 wksht.row(row).write(0, filepath)
 (ruta, filename) = os.path.split(filepath)
 wksht.row(row).write(1, filename)
 n = os.path.splitext(filename)
 p = ruta+'\\'+n[0]+'.prj'
#ruta is the variable that saves the pathfile
 print looking for, p
#I changed to os.path.exists()
 if os.path.exists(p):
  wksht.row(row).write(2, 1)
 else:
  wksht.row(row).write(2, 0)
wrkbk.save('shp3.xls')

#Mensajes para mostar en la consola
SEARCH_PATH = os.getcwd()
TARGET_FILE = os.path.realpath('shp3.xls')
print Buscando en, SEARCH_PATH, and writing to, TARGET_FILE
print Encontrando archivos...
print Escribiendo archivo de Excel...
print Listo.

Thank you so much fro your help!
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] If statement isn't working

2010-10-29 Thread Susana Iraiis Delgado Rodriguez
Hello members:

I'm trying to validate the existence of a file by an if statement, but it
isn't working correctly. The module is a crawler that writes to excel some
attributes from the files it finds.

folders = None
 # look in this (root) folder for files with specified extension
for root, folders, files in os.walk( C:\\ ):
   file_list.extend(os.path.join(root,fi) for fi in files if
fi.endswith(.shp))
wrkbk = Workbook()
 #Add named parameter to allow overwriting cells: cell_overwrite_ok=True
wksht = wrkbk.add_sheet('shp')
#... add the headings to the columns
wksht.row(0).write(0,'ruta')
wksht.row(0).write(1,'archivo')
#write the rows
for row, filepath in enumerate(file_list, start=1):
  wksht.row(row).write(0, filepath)
 (ruta, filename) = os.path.split(filepath)
 wksht.row(row).write(1, filename)

#Here I`m splitting the string filename in base and extension
n = os.path.splitext(filename)
#Getting the base and prj as its extension
 p = n[0]+'.prj'
#validate if p exists
 if os.path.lexists(p):
  wksht.row(row).write(9, 1)
  prj_text = open(p, 'r').read()
  wksht.row(row).write(8,prj_text)
 else:
  wksht.row(row).write(9, 0)
  wksht.row(row).write(8, 'Sin prj, no se puede determinar la proyeccion')

The issue is that it just identifies 3 prj and I have more, befores I
added  prj_text = open(p, 'r').read()
  wksht.row(row).write(8,prj_text) it worked fine and write the correct prj,
but now it doesn't

What am I doing wrong? Hope you can help me
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Python xlwt unicoderror

2010-10-27 Thread Susana Iraiis Delgado Rodriguez
I'm starting to use xlwt to create excel files, my excel sheet is designed
to get information from a python module. The data came from a raster file,
the problem is that some kind of sign or character doesn't allow the file to
be written. This is my script:

import sys, os, time, socket, codecs
from xlwt import Workbook
from osgeo import gdal
from osgeo.gdalconst import *
from PIL import Image

gdal.AllRegister()
file_list = []
folders = None
 # look in this (root) folder for files with specified extension
for root, folders, files in os.walk( C:\\ ):
 file_list.extend(os.path.join(root,fi) for fi in files if
fi.endswith(.tif) or fi.endswith(.tiff) or fi.endswith(.gtif) or
fi.endswith(.ecw) or fi.endswith(.bil) or fi.endswith(.til) or
fi.endswith(.jpeg) or fi.endswith(.img) or fi.endswith(.jpg))
wrkbk = Workbook()
 #Add named parameter to allow overwriting cells: cell_overwrite_ok=True
wksht = wrkbk.add_sheet('raster')
wksht.row(0).write(0,'ruta')
wksht.row(0).write(1,'nombre')
wksht.row(0).write(2,'x_min')
wksht.row(0).write(3,'x_max')
wksht.row(0).write(4,'y_min')
wksht.row(0).write(5,'y_max')
wksht.row(0).write(6,'ancho_pixel')
wksht.row(0).write(7,'alto_pixel')
wksht.row(0).write(8,'num_filas')
wksht.row(0).write(9,'num_columnas')
wksht.row(0).write(10,'num_bandas')
wksht.row(0).write(11,'proyeccion')
wksht.row(0).write(12,'fecha_modificacion')
wksht.row(0).write(13,'maquina_host')
wksht.row(0).write(14,'usuario')

for row, filepath in enumerate(file_list, start=1):
 #Llenar lista de archivos y ruta
 unicode(filepath, errors='ignore')
 wksht.row(row).write(0, filepath)
 #Escribir solo el nombre del archivo
 (ruta, filename) = os.path.split(filepath)
 wksht.row(row).write(1, filename)
 unicode(filename, errors='ignore')
 # Obtener coordenadas x/y
 dataset = gdal.Open(filepath, GA_ReadOnly)
 if dataset is None:
  print 'Could not open...' +filename

 #iNFORMACIoN GEOREFERENCIA
 else:
  xOrigin, yOrigin, pixelWidth, pixelHeight, a, b =
dataset.GetGeoTransform()
  geotransform = dataset.GetGeoTransform(

 #Obtener coordenadas
  x_min = geotransform[0]
  wksht.row(row).write(2,x_min)
  y_max = geotransform[3]
  wksht.row(row).write(5,y_max)
  pixel_width = geotransform[1]
  wksht.row(row).write(6,pixel_width)
  pixel_height = geotransform[5]
  wksht.row(row).write(7,pixel_height)

 #Obtener tamano de la imagen
  rows = dataset.RasterYSize
  cols = dataset.RasterXSize
  bands = dataset.RasterCount

  wksht.row(row).write(8,rows)
  wksht.row(row).write(9,cols)
  wksht.row(row).write(10,bands)

  x_max= (pixel_width - x_min) / pixel_width
  y_min = (y_max - x_min) / pixel_height
  wksht.row(row).write(3,x_max)
  wksht.row(row).write(4,y_min)


 #Obtener la proyeccion
  n = os.path.splitext(filepath)
  tif = n[0]+'.tif'
  tiff = n[0]+'.tiff'
  gtif = n[0]+'.gtif'
  ecw = n[0]+'.ecw'
  bil = n[0]+'.bil'
  til = n[0]+'.til'
  img = n[0]+'.img'
  jpg = n[0]+'.jpg'
  jpeg = n[0]+'.jpeg'
  if os.path.lexists(tif) or os.path.lexists(tiff) or os.path.lexists(gtif)
or os.path.lexists(ecw) or os.path.lexists(bil) or os.path.lexists(til) or
os.path.lexists(jpg) or os.path.lexists(jpeg):
   wksht.row(row).write(11, dataset.GetProjection())
   #print filename
  else:
   wksht.row(row).write(11, No tiene proyeccion)

 #Obtner el nombre del host del archivo
  wksht.row(row).write(13, socket.gethostname())

 #Obtener usuario
  wksht.row(row).write(14,os.environ.get(USERNAME))

 #Obtener fecha de modificacion
   t = time.strftime(%m/%d/%Y %I:%M:%S
%p,time.localtime(os.path.getmtime(filepath)))
  wksht.row(row).write(15, t)

codecs.EncodedFile(wrkbk, UTF8,errors='ignore')
wrkbk.save('rasters.xls')

SEARCH_PATH = os.getcwd()
TARGET_FILE = os.path.realpath('shp.xls')
print Buscando en, SEARCH_PATH, and writing to, TARGET_FILE
print Encontrando archivos...
print Escribiendo archivo de Excel...
print Listo.
The error is:
Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)]
on
win32
Type help, copyright, credits or license for more information.
 import crawler_img
ERROR 4: `C:\Archivos de programa\WinAce\menuimg.img' not recognised as a
suppor
ted file format.
Could not open...menuimg.img
ERROR 4: `C:\Archivos de programa\WinAce\toolimg.img' not recognised as a
suppor
ted file format.
Could not open...toolimg.img
ERROR 4: `C:\Documents and Settings\sinventario\Configuraci¾n local\Archivos
tem
porales de Internet\Content.IE5\46MPK9B5\visitor[6].jpg' not recognised as a
sup
ported file format.
Could not open...visitor[6].jpg
ERROR 4: `C:\Documents and Settings\sinventario\Configuraci¾n local\Archivos
tem
porales de Internet\Content.IE5\46MPK9B5\visitor[7].jpg' not recognised as a
sup
ported file format.
Could not open...visitor[7].jpg
ERROR 4: `C:\Documents and Settings\sinventario\Configuraci¾n local\Archivos
tem
porales de Internet\Content.IE5\46MPK9B5\visitor[8].jpg' not recognised as a
sup
ported file format.
Could not open...visitor[8].jpg
ERROR 4: `C:\Documents and Settings\sinventario\Configuraci¾n 

[Tutor] Python and excel writer: 'ascii' codec can't decode byte 0xf3 in position 49

2010-10-25 Thread Susana Iraiis Delgado Rodriguez
Hello members:

I'm starting an script for geospatial information using python and gdal
binaries, but I have problems saving the data I get into an excel shee. At
the beginning I thought it was because the characters the files have for
some records, but I run the code in a way it saves the path for each file
I'm looking for. The script throws th error:
Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)]
on
win32
Type help, copyright, credits or license for more information.
 import imagen
Traceback (most recent call last):
  File stdin, line 1, in module
  File imagen.py, line 20, in module
wrkbk.save('imagen.xls')
  File C:\Python26\lib\site-packages\xlwt\Workbook.py, line 634, in save
doc.save(filename, self.get_biff_data())
  File C:\Python26\lib\site-packages\xlwt\Workbook.py, line 609, in
get_biff_d
ata
shared_str_table   = self.__sst_rec()
  File C:\Python26\lib\site-packages\xlwt\Workbook.py, line 571, in
__sst_rec
return self.__sst.get_biff_record()
  File C:\Python26\lib\site-packages\xlwt\BIFFRecords.py, line 53, in
get_biff
_record
self._add_to_sst(s)
  File C:\Python26\lib\site-packages\xlwt\BIFFRecords.py, line 66, in
_add_to_
sst
u_str = upack2(s, self.encoding)
  File C:\Python26\lib\site-packages\xlwt\UnicodeUtils.py, line 50, in
upack2
us = unicode(s, encoding)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xf3 in position 49:
ordinal
 not in range(128)

My code is:
import os, time, socket
from xlwt import Workbook
from osgeo import gdal
from osgeo.gdalconst import *
from PIL import Image

gdal.AllRegister()
file_list = []
folders = None
 # look in this (root) folder for files with specified extension
for root, folders, files in os.walk( C:\\ ):
 file_list.extend(os.path.join(root,fi) for fi in files if
fi.endswith(.tif) or fi.endswith(.tiff) or fi.endswith(.gtif) or
fi.endswith(.ecw) or fi.endswith(.bil) or fi.endswith(.til) or
fi.endswith(.jpeg))
wrkbk = Workbook()
wksht = wrkbk.add_sheet('rasters')
wksht.row(0).write(0,'ruta')
for row, filepath in enumerate(file_list, start=1):
 #Llenar lista de archivos y ruta
 wksht.row(row).write(0, filepath)
wrkbk.save('imagen.xls')

Is there a way I can manage this error?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Attempt to overwrite excel cell Python

2010-10-14 Thread Susana Iraiis Delgado Rodriguez
Hi Walter!

I already looked at the code you suggested me to accomplish my goal, I made
some changes on it to match mine, your code is very neat and nice. Here are
some lines I changed:

   - First I did the file search

   file_list = []
   folders = None
   for root, folders, files in os.walk( C:\\ ):
file_list.extend(os.path.join(root,fi) for fi in files if
fi.endswith(.shp))

   - Then I create the excel, and asign the writing to the cells:

   wksht = wrkbk.add_sheet('shp')
   wksht.row(0).write(0,'archivo')
   wksht.row(0).write(1,'x_min')
   wksht.row(0).write(2,'y_min')
   wksht.row(0).write(3,'x_max')
   wksht.row(0).write(4,'y_max')
   wksht.row(0).write(5,'geometria')
   wksht.row(0).write(6,'num_elem')
   wksht.row(0).write(7,'prj')
   wksht.row(0).write(8,'estrutura bd')
   wksht.row(0).write(9,'extent')
   wksht.row(0).write(10,'fecha_modificacion')
   wksht.row(0).write(11,'maquina_host')


   for row, filepath in enumerate(file_list, start=1):
   wksht.row(row).write(0, filepath)
  wrkbk.save('shp.xls')


SEARCH_PATH = os.getcwd()
TARGET_FILE = os.path.realpath('shp.xls')
print Searching in, SEARCH_PATH, and writing to, TARGET_FILE
print Finding files...
print Writing Excel file...
print Done.


2010/10/13 Susana Iraiis Delgado Rodriguez susana.delgad...@utzmg.edu.mx

 Hi Walter!

 I already looked at the code you suggested me to accomplish my goal, I made
 some changes on it to match mine, your code is very neat and nice. Here are
 some lines I changed:

- First I did the file search

file_list = []
folders = None
for root, folders, files in os.walk( C:\\ ):
 file_list.extend(os.path.join(root,fi) for fi in files if
 fi.endswith(.shp))

- Then I create the excel, and asign the writing to the cells:

wksht = wrkbk.add_sheet('shp')
wksht.row(0).write(0,'archivo')
wksht.row(0).write(1,'x_min')
wksht.row(0).write(2,'y_min')
wksht.row(0).write(3,'x_max')
wksht.row(0).write(4,'y_max')
wksht.row(0).write(5,'geometria')
wksht.row(0).write(6,'num_elem')
wksht.row(0).write(7,'prj')
wksht.row(0).write(8,'estrutura bd')
wksht.row(0).write(9,'extent')
wksht.row(0).write(10,'fecha_modificacion')
wksht.row(0).write(11,'maquina_host')


for row, filepath in enumerate(file_list, start=1):
wksht.row(row).write(0, filepath)
   wrkbk.save('shp.xls')


 SEARCH_PATH = os.getcwd()
 TARGET_FILE = os.path.realpath('shp.xls')
 print Searching in, SEARCH_PATH, and writing to, TARGET_FILE
 print Finding files...
 print Writing Excel file...
 print Done.

 2010/10/12 Walter Prins wpr...@gmail.com

 Hi just a quick note -- I included my own recursive call in the code I
 posted last night which is obviously superflous as os.walk() already
 recurses by itself.  So if you looked at it already you may want to look at
 it again.

 Walter



___
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-11 Thread Susana Iraiis Delgado Rodriguez
Hello members!

Thank you all of you for taking the time to answer to my question. I didn´t
expect it will create the controversy we just had in this topic. I don't
mind for the comments of re-inventing the wheel, I'm new in python,
documentation is good but programmers' experience is even better.

The intention of using the os.walk() is because I'm creating a sort of
directory crawler to find every file with the extensions I'm looking for, so
am I in the rigth direction?
The other question is about the excel files management, if I want to
manipulate this data to work it in Excel should I look for an excel library
in python right?
___
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-11 Thread Susana Iraiis Delgado Rodriguez
Hello Walter and members:

I'm working with csv to handle excel, my other was useful to do my new cvs
file. When I open the output file, it has all the information I need, but
all of my lines have the filepath separate by comes, even though it's
supposed to be a complete string; for example: C,:,\,i,n,d,i,c,e,.,s,h,p all
the others have the same format.
Besides I need a row to put in each cell the column names, with:
 
c.writerow([Archivo,x_min,x_max,y_min,y_max,geometria,num_ele,prj,estructura
bd,extent,fecha_modificacion,maquina_host]). But all tha names gather
in the same row and I want my pathfile to place under the Archivo column,
but I couldn't do it.



2010/10/11 Walter Prins wpr...@gmail.com



 On 11 October 2010 14:37, Susana Iraiis Delgado Rodriguez 
 susana.delgad...@utzmg.edu.mx wrote:

 The other question is about the excel files management, if I want to
 manipulate this data to work it in Excel should I look for an excel library
 in python right?


 Yes. I already mentioned one (in my view good) option in my original reply
 to you.   The xlwt module works quite well for generating Excel files (with
 expectable limitations) from any platform that Python's available on (e.g.
 including non-Windows.)  and thus does not require Excel to be available on
 the machine you're producing the file on.

 If however you are running on Windows and have Excel installed, you could
 consider driving the real Excel via COM automation, which will guarantee you
 get desired results including formatting, charts etc, and will ensure you
 have full access to all the functionality Excel exposes via its COM object
 model.

 If your requirements on the other hand simple enough then Joel's suggestion
 to use CSV is probably preferable.  (The KISS principle: Keep It Small 
 Simple)

 There's also the possibility to look into generating .xlsx files (e.g. XML
 based Office format files.)  Theoretically you should be able to generate
 the correctly structured XML independent of Excel and have it open in
 Excel.  I suspect that may be rather painful though (have never tried this
 myself) andam almost reluctant to even mention this option, so caveat
 emptor.

 Walter

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


[Tutor] Attempt to overwrite excel cell Python

2010-10-11 Thread Susana Iraiis Delgado Rodriguez
Hello members:

I'm using xlwt from python to work with excel, I'm developing some sort of
system crawler to look for all the files ending with .shp, I took a look to
csv, but I didn't understand it. Now, I have to create a .xls where people
can save information from shp files, but first I have to create the excel
and add a row for column names:

import os
from xlwt import Workbook
wb = Workbook()
ws = wb.add_sheet('shp')
ws.row(0).write(0,'archivo')
ws.row(0).write(1,'x_min')
ws.row(0).write(2,'y_min')
ws.row(0).write(3,'x_max')
ws.row(0).write(4,'y_max')
ws.row(0).write(5,'geometria')
ws.row(0).write(6,'num_elem')
ws.row(0).write(7,'prj')
ws.row(0).write(8,'estrutura bd')
ws.row(0).write(9,'extent')
ws.row(0).write(10,'fecha_modificacion')
ws.row(0).write(11,'maquina_host')

Then I have to do the crawler part to have the directory I want:
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) ]
 for f in filelist:
  allfiles.append(f)

Now I want to get the name of the file and write it uder the column
Archivo, the variable i has the name of each file:
for i in allfiles:
 print i
ws.row(1).write(0,i)
wb.save('shp.xls')

But when I run it, it throws me the error:
*Exception*: *Attempt to overwrite cell*: sheetname='shp' rowx=1 colx=0,
don't know what is wrong
___
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 susana.delgad...@utzmg.edu.mx

 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 taser...@gmail.com

  On Thu, Oct 7, 2010 at 12:48 PM, taserian taser...@gmail.com 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 susana.delgad...@utzmg.edu.mx

 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 susana.delgad...@utzmg.edu.mx

  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 taser...@gmail.com

  On Thu, Oct 7, 2010 at 12:48 PM, taserian taser...@gmail.com 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

[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


[Tutor] PYTHON QUOTES ISSUE

2010-10-07 Thread Susana Iraiis Delgado Rodriguez
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?
___
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-07 Thread 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 taser...@gmail.com

  On Thu, Oct 7, 2010 at 12:48 PM, taserian taser...@gmail.com 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] EXECUTING PYTHON AND SQL STAMENTS

2010-10-05 Thread Susana Iraiis Delgado Rodriguez
Hello Norman:

Thank you for taking the time to answer. I already changed my os.system()
for your code. I got an error, when I executed this:
os.system( 'C:/Archivos de programa/FWTools2.4.7/bin/ogr2ogr.exe ' +arg1
+ -where +arg2 +  +arg3)
it throws me that C:/Archivos  is not recognized as an executable external
or internal command, programm or file.
If you really have other opton to fix my problem I'll be thankful because I
don't have any idea to make this code useful.
Thank you
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] EXECUTING PYTHON AND SQL STAMENTS

2010-10-05 Thread Susana Iraiis Delgado Rodriguez
Hello, I already solved the problem, I change all the code, instead of using
os.system I changed to subprocess.Popen() and it worked fine:

import shlex, subprocess
def process():
 print Ingresa en el siguiente orden:
 print Nombre del nuevo mapa.shp Nombre de la capa Nombre del mapa
original
 command_line = raw_input()
 args = shlex.split(command_line)
 p = subprocess.Popen(['C:/Archivos de
programa/FWTools2.4.7/bin/ogr2ogr', args[0], '-where', args[1], args[2]])
 if p:
  print Mapa generado
process()

Now the user has to enter 3 arguments an finally it worked. I have a
question, how can I tell the user if p execute ok? because even thouhg I
entered wrong parameters, it prints Mapa generado. This line should only
appears if the arguments are acceptable.

2010/10/5 Susana Iraiis Delgado Rodriguez susana.delgad...@utzmg.edu.mx

 Hello Norman:

 Thank you for taking the time to answer. I already changed my os.system()
 for your code. I got an error, when I executed this:
  os.system( 'C:/Archivos de programa/FWTools2.4.7/bin/ogr2ogr.exe '
 +arg1 + -where +arg2 +  +arg3)
 it throws me that C:/Archivos  is not recognized as an executable
 external or internal command, programm or file.
 If you really have other opton to fix my problem I'll be thankful because I
 don't have any idea to make this code useful.
 Thank you

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


[Tutor] EXECUTING PYTHON AND SQL STAMENTS

2010-10-04 Thread Susana Iraiis Delgado Rodriguez
I'm developing a module to execute an external command. The module executes
the command, but in order to make my code useful I have to enter some sql
staments. This is my code:
from dbf import *
from osgeo import ogr
import os
import sys
def call():
  print Ingresa el nombre para el nuevo mapa
  arg1 = R1G-GEODESIA2.shp
  print arg1
  print Ingresa la condicion
  arg2 = LAYER = 'R1G-GEODESIA'
  print arg2
  print Ingresa el nombre del mapa original
  arg3 = 'C:/Python26/tapalpa_05_plani_point.shp'
  print arg3
  os.system('C:/Archivos de programa/FWTools2.4.7/setfw')
  os.system('C:/Archivos de programa/FWTools2.4.7/bin/ogr2ogr.exe'+ 
+arg1 + + -where + + arg2 +  +arg3)
call()
The problem is that when I run the module it throws the error:
Unable to open datasource`arg3' with the following drivers.
ESRI Shapefile
MapInfo File
UK .NTFSDTS
TIGER
S57
DGN
VRT
REC
Memory
BNA
CSV
NAS
GML
GPX
KML
GeoJSON
Interlis 1
Interlis 2
GMT
SQLite
ODBC
PGeo
OGDI
PostgreSQL
MySQL
XPlane
AVCBin
AVCE00
DXF
Geoconcept
GeoRSS
GPSTrackMaker
VFK
Can you help me please?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Runnig a windows.exe from python

2010-09-30 Thread Susana Iraiis Delgado Rodriguez
Hello !

I apoligize for the format of my last message, I didn't realize that putting
my text in bold format will show those asterisks.
By the way you're Alan, for the pythom module I first had to read my
arguments and passed them to the os.system(), it worked. Now when I execute
this command, in my normal DOS Windows, I must change to another path before
I run the .exe, I don't know how to tell this to my python module. This is
my code:

from dbf import *
from osgeo import ogr
import os
import sys
def call():
  os.chdir('C:\Python26')
  arg1 = R1G-GEODESIA2.shp
  arg2 = LAYER = 'R1G-GEODESIA'
  arg4 = tapalpa_05_plani_point.shp
  os.system('C:/Archivos de programa/FWTools2.4.7/setfw')
  os.system('C:/Archivos de programa/FWTools2.4.7/bin/ogr2ogr.exe'+ 
+arg1 + + -where + + arg3 +  +arg4)
call()

If I run it, it shows me the following error:
Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)]
on
win32
Type help, copyright, credits or license for more information.
 import fw
Ingresa el nombre para el nuevo mapa
R1G-GEODESIA2.shp
Ingresa la condicion
LAYER = 'R1G-GEODESIA'
Ingresa el nombre del mapa original
tapalpa_05_plani_point.shp
FAILURE:
Unable to open datasource `arg3' with the following drivers.
  - ESRI Shapefile
  - MapInfo File
  - UK .NTF
  - SDTS
  - TIGER
  - S57
  - DGN
  - VRT
  - REC
  - Memory
  - BNA
  - CSV
  - NAS
  - GML
  - GPX
  - KML
  - GeoJSON
  - Interlis 1
  - Interlis 2
  - GMT
  - SQLite
  - ODBC
  - PGeo
  - OGDI
  - PostgreSQL
  - MySQL
  - XPlane
  - AVCBin
  - AVCE00
  - DXF
  - Geoconcept
  - GeoRSS
  - GPSTrackMaker
  - VFK

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


Re: [Tutor] Writing a txt from dbf

2010-09-29 Thread Susana Iraiis Delgado Rodriguez
Hello Steven!

Your guess was rigth, that's what I'm looking for!  I need an output as:
beta
gamma
etc...
but I'm showing betagammaetc..

What can I do to my code to get the first ouput? By the way thanks for
answering!
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Writing txt from dbf

2010-09-29 Thread Susana Iraiis Delgado Rodriguez
Thanks Steven and Alan, your recommendation worked perfectly!
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Runnig a windows.exe from python

2010-09-29 Thread Susana Iraiis Delgado Rodriguez
Hello everyone:

I'm working in a simple python module to run a external command, this
command is named ogr2ogr.exe . When I execute my python script :

*import os
def call():
 os.system(' C:\\Archivos de programa\\FWTools2.4.7\\bin\\ogr2ogr.exe
')*
* raw_input()*
*call()*
It runs, but if I want to enter arguments: *ogr2ogr*  to test my .exe, it
shows me an error *ogr2ogr is not define, *any suggestion?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Writing a txt from dbf

2010-09-28 Thread Susana Iraiis Delgado Rodriguez
Hello dear pythonists:

I'm developing an application in python, I'm new using this programming
language I used to work with Java, but in my job my superiors suggested me
to develop in this language.
I'm trying to read a dbf file, I already done it but my code shows me all
the lines without spaces, I want it toshow line per line and then write the
lines into a plain txt file. My code is:

from dbf import *
from string import strip
import sys
def demo1():
 a = open (archivo.txt,w)
 dbf = Dbf('tapalpa_05_plani_point.dbf',new=False)

 for k in dbf:
  print '%s'%(strip(k[2]))

  l=()
  l=(strip(k[2]))
  a.write(l)

 dbf.close()
 a.close()


demo1()
I hope you can help me.
Thank you!
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor