[Tutor] Unusual pathfile
Susana Iraiis Delgado Rodriguez
susana.delgado_s at utzmg.edu.mx
Tue Sep 13 17:41:26 CEST 2011
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:
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'
dirname1 =
tkFileDialog.askdirectory(parent=root,initialdir="/",title='Selecciona la
ruta a escanear')
if len(dirname1 ) > 0:
print "You chose %s" % dirname1
dir = dirname1
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 buscar():
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)
shapeData = ogr.Open(filepath.encode(filesystemencoding))
if shapeData is None:
shp = 'Error al abrir el archivo ' + filepath.encode(filesystemencoding)
print shp
log.write(shp+"\n")
else:
print 'Trabajando en: ' +filepath
layer = shapeData.GetLayer()
feature = layer.GetNextFeature()
x_y = layer.GetExtent()
#x_min
x1 = x_y[0]
#x_max
x2 = x_y[1]
#y_min
y1 = x_y[2]
#y_max
y2 = x_y[3]
#Escribir el tipo de geometria del shp. 1=Point, 2=LineString,
3=Polygon
defn = layer.GetLayerDefn()
geo = defn.GetGeomType()
#Comenzar el featurecount()
cuenta = layer.GetFeatureCount()
proy = layer.GetSpatialRef()
prjtext = ''+str(proy)+''
###
n = os.path.splitext(filepath)
p = n[0]+'.prj'
shx = n[0]+'.shx'
#shx_msj = 'Error al abrir el archivo' +shx
dbf = n[0]+'.dbf'
#dbf_msj = 'Error al abrir el archivo' +dbf
filepath = ''+filepath+''
filename = ''+filename+''
t = time.strftime("%m/%d/%Y %I:%M:%S
%p",time.localtime(os.path.getmtime(filepath)))
modificacion = ''+t+''
crdt = time.strftime("%m/%d/%Y %I:%M:%S
%p",time.localtime(os.path.getctime(filepath)))
crea = ''+crdt+''
lt_acc = time.strftime("%m/%d/%Y %I:%M:%S
%p",time.localtime(os.path.getatime(filepath)))
acceso = ''+lt_acc+''
s = os.path.getsize(filepath)
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
#Obtener usuario
usuario = os.environ.get("USERNAME")
user = ''+usuario+''
host = socket.gethostname()
maquina = ''+host+''
if os.path.exists(shx):
print '.'
shx1 = os.path.getsize(shx)
#kb2 = sizeof_fmt(shx1)
else:
log.write('No existe el archivo ' +shx+"\n")
if os.path.exists(dbf):
print '.'
else:
log.write('No existe el archivo ' +dbf+"\n")
if os.path.exists(p):
#Si existe, asignar 1
p1 = os.path.getsize(p)
total = sizeof_fmt(s+shx1+p1)
aRow= [ directorio, filename, x1, x2, y1, y2, geo, cuenta, 1, prjtext,
crea, modificacion, acceso, total, maquina, user]
writer.writerow(aRow)
else:
#Sino asignar 0
#no_prj = 'Sin prj, no se puede determinar la
proyeccion'
total = sizeof_fmt(s+shx1)
aRow1= [ directorio, filename, x1, x2, y1, y2, geo, cuenta, 0, prjtext,
crea, modificacion, acceso, total, maquina, user]
writer.writerow(aRow1)
log.close()
f.close()
print "El archivo esta listo"
root = Tk()
top = Toplevel() #Llamo una nueva ventana #Dimensiones de la ventana
root.minsize(400,200) #Barra de herramientas
toolbar = Frame(root) #Botones
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_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.gauld at 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 at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110913/ad481183/attachment.html>
More information about the Tutor
mailing list