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

Susana Iraiis Delgado Rodriguez susana.delgado_s at utzmg.edu.mx
Thu Mar 24 16:22:56 CET 2011


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"
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110324/15b260cb/attachment.html>


More information about the Tutor mailing list