OGR: Load layer with sql statement and write to new data setOGR FeatureCount returns '-1' with OSM dataNew...

Should an enameled cast iron pan be seasoned?

Why are < or > requried to use /dev/tcp

LWC - Local Dev - How can I run the local server on HTTPS?

I found a password with hashcat, but it doesn't work

How to maintain a closed environment for one person for a long period of time

Why do all the teams that I have worked with always finish a sprint without completion of all the stories?

Did the CIA blow up a Siberian pipeline in 1982?

career in signal processing

What is "industrial ethernet"?

How does DC work with natural 20?

Is there a difference between an NFC and RFID chip?

Can I enter the UK for 24 hours from a Schengen area, holding an Indian passport?

Is Famished Paladin and Resplendent Mentor a legal infinite life combo?

What determines the direction in which motor proteins go?

What happened to Steve's Shield in Iron Man 2?

Is there any proof that high saturation and contrast makes a picture more appealing in social media?

Heavily limited premature compiler translates text into excecutable python code

Trainee keeps passing deadlines for independent learning

RandomInteger with equal number of 1 and -1

Do I need a shock-proof watch for cycling?

How many people are necessary to maintain modern civilisation?

Greeting with "Ho"

How can you guarantee that you won't change/quit job after just couple of months?

Why isn't my calculation that we should be able to see the sun well beyond the observable universe valid?



OGR: Load layer with sql statement and write to new data set


OGR FeatureCount returns '-1' with OSM dataNew attribute creation using ogr and regexAppend ArcGIS feature layer data using GDAL/OGR APIIntersect polyline and polygon with ogrHow to read SQL request result executed with Python OGR?How to create line/polygon shapefiles from geojson using gdal in Python?Write coordinates to new shp file columns with OGROGR SQL Intersect layer slow to iterateCan't set OGR layer geometry type in PythonC++ OGR GDAL Set spatial reference of new layer






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ margin-bottom:0;
}







2















I am having difficulties after loading a shapefile with a sql statement with ogr.
The layer and its features seem to be correctly loaded. Still I am not able to write them into a new shapefile or pass the layer to the gdal_rasterize function.
The shapefile remains an empty file and the raster has the typical no input/something wrong happend values from 1.79..e+308 to -1.79..e+308 (not visualized in QGIS).
Code example for the creation of the shapefile (paths are omitted):



file = ogr.Open(file_path)
sql = 'Select * From {} where {} <= 5'.format(layer_name, "CS")
tmp_layer = file.ExecuteSQL(sql)
print(tmp_layer)
>>><osgeo.ogr.Layer; proxy of <Swig Object of type 'OGRLayerShadow *' at 0x00000214D99617E0> >
for feat in tmp_layer:
print(feat.GetField('CS'))
>>>(prints the field of the subset of features as expected)
drv = ogr.GetDriverByName("ESRI Shapefile")
out_ds = drv.CreateDataSource(output_folder + '/asd.shp')
proj = tmp_layer.GetSpatialRef()
layer = out_ds.CreateLayer('asd', proj, ogr.wkbMultiPolygon)
# copy the schema of the original shapefile to the destination shapefile
lyr_def = tmp_layer.GetLayerDefn()
for i in range(lyr_def.GetFieldCount()):
layer.CreateField(lyr_def.GetFieldDefn(i))
#write features from tmp_layer to new layer
for feat in tmp_layer:
layer.CreateFeature(feat)
out_ds = layer = None


I am not able to find my mistake and would appreciate some help :)










share|improve this question























  • Does it work without the filtering? Does it work with different data (try naturalearthdata.com since that is free for everyone to use)?

    – bugmenot123
    8 hours ago











  • Oh damn... I tried so much and I dont know what wrent wrong before - because I am quite sure I tested it without the iteration over the features. It seems that while iterating over the features these get consumed and are not available anymore... And thats the whole problem! (So it didnt work without the sql statement)

    – gilla
    8 hours ago


















2















I am having difficulties after loading a shapefile with a sql statement with ogr.
The layer and its features seem to be correctly loaded. Still I am not able to write them into a new shapefile or pass the layer to the gdal_rasterize function.
The shapefile remains an empty file and the raster has the typical no input/something wrong happend values from 1.79..e+308 to -1.79..e+308 (not visualized in QGIS).
Code example for the creation of the shapefile (paths are omitted):



file = ogr.Open(file_path)
sql = 'Select * From {} where {} <= 5'.format(layer_name, "CS")
tmp_layer = file.ExecuteSQL(sql)
print(tmp_layer)
>>><osgeo.ogr.Layer; proxy of <Swig Object of type 'OGRLayerShadow *' at 0x00000214D99617E0> >
for feat in tmp_layer:
print(feat.GetField('CS'))
>>>(prints the field of the subset of features as expected)
drv = ogr.GetDriverByName("ESRI Shapefile")
out_ds = drv.CreateDataSource(output_folder + '/asd.shp')
proj = tmp_layer.GetSpatialRef()
layer = out_ds.CreateLayer('asd', proj, ogr.wkbMultiPolygon)
# copy the schema of the original shapefile to the destination shapefile
lyr_def = tmp_layer.GetLayerDefn()
for i in range(lyr_def.GetFieldCount()):
layer.CreateField(lyr_def.GetFieldDefn(i))
#write features from tmp_layer to new layer
for feat in tmp_layer:
layer.CreateFeature(feat)
out_ds = layer = None


I am not able to find my mistake and would appreciate some help :)










share|improve this question























  • Does it work without the filtering? Does it work with different data (try naturalearthdata.com since that is free for everyone to use)?

    – bugmenot123
    8 hours ago











  • Oh damn... I tried so much and I dont know what wrent wrong before - because I am quite sure I tested it without the iteration over the features. It seems that while iterating over the features these get consumed and are not available anymore... And thats the whole problem! (So it didnt work without the sql statement)

    – gilla
    8 hours ago














2












2








2








I am having difficulties after loading a shapefile with a sql statement with ogr.
The layer and its features seem to be correctly loaded. Still I am not able to write them into a new shapefile or pass the layer to the gdal_rasterize function.
The shapefile remains an empty file and the raster has the typical no input/something wrong happend values from 1.79..e+308 to -1.79..e+308 (not visualized in QGIS).
Code example for the creation of the shapefile (paths are omitted):



file = ogr.Open(file_path)
sql = 'Select * From {} where {} <= 5'.format(layer_name, "CS")
tmp_layer = file.ExecuteSQL(sql)
print(tmp_layer)
>>><osgeo.ogr.Layer; proxy of <Swig Object of type 'OGRLayerShadow *' at 0x00000214D99617E0> >
for feat in tmp_layer:
print(feat.GetField('CS'))
>>>(prints the field of the subset of features as expected)
drv = ogr.GetDriverByName("ESRI Shapefile")
out_ds = drv.CreateDataSource(output_folder + '/asd.shp')
proj = tmp_layer.GetSpatialRef()
layer = out_ds.CreateLayer('asd', proj, ogr.wkbMultiPolygon)
# copy the schema of the original shapefile to the destination shapefile
lyr_def = tmp_layer.GetLayerDefn()
for i in range(lyr_def.GetFieldCount()):
layer.CreateField(lyr_def.GetFieldDefn(i))
#write features from tmp_layer to new layer
for feat in tmp_layer:
layer.CreateFeature(feat)
out_ds = layer = None


I am not able to find my mistake and would appreciate some help :)










share|improve this question














I am having difficulties after loading a shapefile with a sql statement with ogr.
The layer and its features seem to be correctly loaded. Still I am not able to write them into a new shapefile or pass the layer to the gdal_rasterize function.
The shapefile remains an empty file and the raster has the typical no input/something wrong happend values from 1.79..e+308 to -1.79..e+308 (not visualized in QGIS).
Code example for the creation of the shapefile (paths are omitted):



file = ogr.Open(file_path)
sql = 'Select * From {} where {} <= 5'.format(layer_name, "CS")
tmp_layer = file.ExecuteSQL(sql)
print(tmp_layer)
>>><osgeo.ogr.Layer; proxy of <Swig Object of type 'OGRLayerShadow *' at 0x00000214D99617E0> >
for feat in tmp_layer:
print(feat.GetField('CS'))
>>>(prints the field of the subset of features as expected)
drv = ogr.GetDriverByName("ESRI Shapefile")
out_ds = drv.CreateDataSource(output_folder + '/asd.shp')
proj = tmp_layer.GetSpatialRef()
layer = out_ds.CreateLayer('asd', proj, ogr.wkbMultiPolygon)
# copy the schema of the original shapefile to the destination shapefile
lyr_def = tmp_layer.GetLayerDefn()
for i in range(lyr_def.GetFieldCount()):
layer.CreateField(lyr_def.GetFieldDefn(i))
#write features from tmp_layer to new layer
for feat in tmp_layer:
layer.CreateFeature(feat)
out_ds = layer = None


I am not able to find my mistake and would appreciate some help :)







gdal ogr






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked 9 hours ago









gillagilla

1086




1086













  • Does it work without the filtering? Does it work with different data (try naturalearthdata.com since that is free for everyone to use)?

    – bugmenot123
    8 hours ago











  • Oh damn... I tried so much and I dont know what wrent wrong before - because I am quite sure I tested it without the iteration over the features. It seems that while iterating over the features these get consumed and are not available anymore... And thats the whole problem! (So it didnt work without the sql statement)

    – gilla
    8 hours ago



















  • Does it work without the filtering? Does it work with different data (try naturalearthdata.com since that is free for everyone to use)?

    – bugmenot123
    8 hours ago











  • Oh damn... I tried so much and I dont know what wrent wrong before - because I am quite sure I tested it without the iteration over the features. It seems that while iterating over the features these get consumed and are not available anymore... And thats the whole problem! (So it didnt work without the sql statement)

    – gilla
    8 hours ago

















Does it work without the filtering? Does it work with different data (try naturalearthdata.com since that is free for everyone to use)?

– bugmenot123
8 hours ago





Does it work without the filtering? Does it work with different data (try naturalearthdata.com since that is free for everyone to use)?

– bugmenot123
8 hours ago













Oh damn... I tried so much and I dont know what wrent wrong before - because I am quite sure I tested it without the iteration over the features. It seems that while iterating over the features these get consumed and are not available anymore... And thats the whole problem! (So it didnt work without the sql statement)

– gilla
8 hours ago





Oh damn... I tried so much and I dont know what wrent wrong before - because I am quite sure I tested it without the iteration over the features. It seems that while iterating over the features these get consumed and are not available anymore... And thats the whole problem! (So it didnt work without the sql statement)

– gilla
8 hours ago










2 Answers
2






active

oldest

votes


















2














When you iterate over the layer it essentially calls lyr.GetNextFeature(). After the last feature the pointer remains at the end which is why when you iterate over the layer the second time it doesn't find any features.



If you plan on iterating over the layer more than once you need to make sure you call lyr.ResetReading() to reset the pointer to the first feature.



#write features from tmp_layer to new layer
tmp_layer.ResetReading()
for feat in tmp_layer:
layer.CreateFeature(feat)





share|improve this answer































    1














    The iteration over the features seem to consume these features like in an interator. Thus omitting the iteration for printing will solve the problem.






    share|improve this answer


























    • You can accept your answer so future readers know what the solution is.

      – Marcelo Villa
      4 hours ago












    Your Answer








    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "79"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fgis.stackexchange.com%2fquestions%2f326144%2fogr-load-layer-with-sql-statement-and-write-to-new-data-set%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2














    When you iterate over the layer it essentially calls lyr.GetNextFeature(). After the last feature the pointer remains at the end which is why when you iterate over the layer the second time it doesn't find any features.



    If you plan on iterating over the layer more than once you need to make sure you call lyr.ResetReading() to reset the pointer to the first feature.



    #write features from tmp_layer to new layer
    tmp_layer.ResetReading()
    for feat in tmp_layer:
    layer.CreateFeature(feat)





    share|improve this answer




























      2














      When you iterate over the layer it essentially calls lyr.GetNextFeature(). After the last feature the pointer remains at the end which is why when you iterate over the layer the second time it doesn't find any features.



      If you plan on iterating over the layer more than once you need to make sure you call lyr.ResetReading() to reset the pointer to the first feature.



      #write features from tmp_layer to new layer
      tmp_layer.ResetReading()
      for feat in tmp_layer:
      layer.CreateFeature(feat)





      share|improve this answer


























        2












        2








        2







        When you iterate over the layer it essentially calls lyr.GetNextFeature(). After the last feature the pointer remains at the end which is why when you iterate over the layer the second time it doesn't find any features.



        If you plan on iterating over the layer more than once you need to make sure you call lyr.ResetReading() to reset the pointer to the first feature.



        #write features from tmp_layer to new layer
        tmp_layer.ResetReading()
        for feat in tmp_layer:
        layer.CreateFeature(feat)





        share|improve this answer













        When you iterate over the layer it essentially calls lyr.GetNextFeature(). After the last feature the pointer remains at the end which is why when you iterate over the layer the second time it doesn't find any features.



        If you plan on iterating over the layer more than once you need to make sure you call lyr.ResetReading() to reset the pointer to the first feature.



        #write features from tmp_layer to new layer
        tmp_layer.ResetReading()
        for feat in tmp_layer:
        layer.CreateFeature(feat)






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered 4 hours ago









        AliAli

        3,1341822




        3,1341822

























            1














            The iteration over the features seem to consume these features like in an interator. Thus omitting the iteration for printing will solve the problem.






            share|improve this answer


























            • You can accept your answer so future readers know what the solution is.

              – Marcelo Villa
              4 hours ago
















            1














            The iteration over the features seem to consume these features like in an interator. Thus omitting the iteration for printing will solve the problem.






            share|improve this answer


























            • You can accept your answer so future readers know what the solution is.

              – Marcelo Villa
              4 hours ago














            1












            1








            1







            The iteration over the features seem to consume these features like in an interator. Thus omitting the iteration for printing will solve the problem.






            share|improve this answer















            The iteration over the features seem to consume these features like in an interator. Thus omitting the iteration for printing will solve the problem.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited 4 hours ago









            Marcelo Villa

            1,4971818




            1,4971818










            answered 8 hours ago









            gillagilla

            1086




            1086













            • You can accept your answer so future readers know what the solution is.

              – Marcelo Villa
              4 hours ago



















            • You can accept your answer so future readers know what the solution is.

              – Marcelo Villa
              4 hours ago

















            You can accept your answer so future readers know what the solution is.

            – Marcelo Villa
            4 hours ago





            You can accept your answer so future readers know what the solution is.

            – Marcelo Villa
            4 hours ago


















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Geographic Information Systems Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fgis.stackexchange.com%2fquestions%2f326144%2fogr-load-layer-with-sql-statement-and-write-to-new-data-set%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Hudson River Historic District Contents Geography History The district today Aesthetics Cultural...

            The number designs the writing. Feandra Aversely Definition: The act of ingrafting a sprig or shoot of one...

            Ayherre Geografie Demografie Externe links Navigatiemenu43° 23′ NB, 1° 15′ WL43° 23′ NB, 1°...