OGR: Load layer with sql statement and write to new data setOGR 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

Heavily limited premature compiler translates text into excecutable python code

Hit the Bulls Eye with T in the Center

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

Why don't countries like Japan just print more money?

Counterfeit checks were created for my account. How does this type of fraud work?

Why does Linux list NVMe drives as /dev/nvme0 instead of /dev/sda?

Trainee keeps passing deadlines for independent learning

"Correct me if I'm wrong"

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

Understanding the reasoning of the woman who agreed with Shlomo to "cut the baby in half"

Can Ogre clerics use Purify Food and Drink on humanoid characters?

Similarity score: Can Sklearn SVR predict values greater than 1 and less than 0?

Is declining an undergraduate award which causes me discomfort appropriate?

Cut the gold chain

Shooting someone's past self using special relativity

Did the CIA blow up a Siberian pipeline in 1982?

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

RandomInteger with equal number of 1 and -1

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

Has there been any indication at all that further negotiation between the UK and EU is possible?

Is there any difference between Т34ВМ1 and КМ1858ВМ1/3?

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

King or Queen-Which piece is which?

Putting a plot inside a tab



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
    7 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
    7 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
    7 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
    7 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 8 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
    7 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
    7 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
    7 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
    7 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
7 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
7 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
7 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
7 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 3 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 3 hours ago









            Marcelo Villa

            1,4971818




            1,4971818










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

            Canceling a color specificationRandomly assigning color to Graphics3D objects?Default color for Filling in Mathematica 9Coloring specific elements of sets with a prime modified order in an array plotHow to pick a color differing significantly from the colors already in a given color list?Detection of the text colorColor numbers based on their valueCan color schemes for use with ColorData include opacity specification?My dynamic color schemes

            Invision Community Contents History See also References External links Navigation menuProprietaryinvisioncommunity.comIPS Community ForumsIPS Community Forumsthis blog entry"License Changes, IP.Board 3.4, and the Future""Interview -- Matt Mecham of Ibforums""CEO Invision Power Board, Matt Mecham Is a Liar, Thief!"IPB License Explanation 1.3, 1.3.1, 2.0, and 2.1ArchivedSecurity Fixes, Updates And Enhancements For IPB 1.3.1Archived"New Demo Accounts - Invision Power Services"the original"New Default Skin"the original"Invision Power Board 3.0.0 and Applications Released"the original"Archived copy"the original"Perpetual licenses being done away with""Release Notes - Invision Power Services""Introducing: IPS Community Suite 4!"Invision Community Release Notes

            François Viète Contents Biography Work and thought Bibliography See also Notes Further reading External links Navigation menup. 21Google Bookspp. 75–77Google BooksDe thou (from University of Saint Andrews)ArchivedGoogle BooksGoogle BooksGoogle BooksGoogle booksGoogle Bookscc-parthenay.frL'histoire universelle (fr)Universal History (en)ArchivedAdsabs.harvard.eduPagesperso-orange.frArchive.orgChikara Sasaki. Descartes' mathematical thought p.259Google BooksGoogle BooksGoogle Bookspp. 152 and onwardGoogle BooksGoogle BooksScribd.comGoogle Books1257-7979Google BooksGoogle BooksGoogle BooksGoogle BooksGoogle BooksGoogle BooksGallica.bnf.frGoogle BooksGoogle Books"François Viète"Francois Viète: Father of Modern Algebraic NotationThe Lawyer and the GamblerAbout TarporleySite de Jean-Paul GuichardL'algèbre nouvelle"About the Harmonicon"cb120511976(data)1188044800000 0001 0913 5903n82164680ola2013766880073431702w6vt1sb70287374827140948071409480