Merge all shp files in a folder into one with a new field populated with the source filename











up vote
3
down vote

favorite












Want to merge all shp files in a folder into one with a new field populated with the source filename. Not getting any errors but not getting any outputs.



Code originally taken from (How to add field with filename when merging shapefiles with ogr2ogr?)



# merge_shps.py
import os
path = "C:TEMPSWS_SUDSCadastral_Maps" # path to your folder of .shp files
merge = "SWS_INSPIRE" # this will be the name of your merged result
directory = os.listdir(path)
count = 0
for filename in directory:
print "n" + filename + "n"
if ".SHP" in filename.upper() and not ".XML" in filename.upper():
# On the first pass, create a clone and add the filename column.
if count == 0:
# Make a clone (matt wilkie)..
cmd = 'ogr2ogr ' + path + '\' + merge + '.shp ' + path + '\' + filename + ' -where "FID < 0"'
print "n" + cmd + "n"
os.system(cmd)
# Add the field (j03lar50n)..
cmd = 'ogrinfo ' + path + '\' + merge + '.shp -sql "ALTER TABLE ' + merge + ' ADD COLUMN filename character(50)"'
print "n" + cmd + "n"
os.system(cmd)
# Now populate the data (capooti)..
print "Merging: " + str(filename)
# You'll need the filename without the .shp extension for the OGR_SQL..
filenameNoExt = filename.replace(".shp","")
cmd = 'ogr2ogr -f "esri shapefile" -update -append "' +
path + '\' + merge + '.shp" "' +
path + '\' + filename +'"'
' -sql "SELECT '' + filename + '' AS filename, * FROM ' + filenameNoExt + '"'
# Uncomment this line to spit the ogr2ogr sentence to the terminal..
print "n" + cmd + "n"
os.system(cmd)
count += 1









share|improve this question









New contributor




Alex Gagnon is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




















  • Hi Alex, I've had a go at running the code you've posted and it executes without issue. I get a shp file called SWS_INSPIRE in the same folder as the shp files to be merged containing the merged files. Do all of your shp files contain the same type of geometry - are they all points or all polygons...?
    – ian
    17 hours ago










  • Use os.path.join to join paths and filenames together instead of things like this path + '\' + filename
    – BERA
    15 hours ago















up vote
3
down vote

favorite












Want to merge all shp files in a folder into one with a new field populated with the source filename. Not getting any errors but not getting any outputs.



Code originally taken from (How to add field with filename when merging shapefiles with ogr2ogr?)



# merge_shps.py
import os
path = "C:TEMPSWS_SUDSCadastral_Maps" # path to your folder of .shp files
merge = "SWS_INSPIRE" # this will be the name of your merged result
directory = os.listdir(path)
count = 0
for filename in directory:
print "n" + filename + "n"
if ".SHP" in filename.upper() and not ".XML" in filename.upper():
# On the first pass, create a clone and add the filename column.
if count == 0:
# Make a clone (matt wilkie)..
cmd = 'ogr2ogr ' + path + '\' + merge + '.shp ' + path + '\' + filename + ' -where "FID < 0"'
print "n" + cmd + "n"
os.system(cmd)
# Add the field (j03lar50n)..
cmd = 'ogrinfo ' + path + '\' + merge + '.shp -sql "ALTER TABLE ' + merge + ' ADD COLUMN filename character(50)"'
print "n" + cmd + "n"
os.system(cmd)
# Now populate the data (capooti)..
print "Merging: " + str(filename)
# You'll need the filename without the .shp extension for the OGR_SQL..
filenameNoExt = filename.replace(".shp","")
cmd = 'ogr2ogr -f "esri shapefile" -update -append "' +
path + '\' + merge + '.shp" "' +
path + '\' + filename +'"'
' -sql "SELECT '' + filename + '' AS filename, * FROM ' + filenameNoExt + '"'
# Uncomment this line to spit the ogr2ogr sentence to the terminal..
print "n" + cmd + "n"
os.system(cmd)
count += 1









share|improve this question









New contributor




Alex Gagnon is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




















  • Hi Alex, I've had a go at running the code you've posted and it executes without issue. I get a shp file called SWS_INSPIRE in the same folder as the shp files to be merged containing the merged files. Do all of your shp files contain the same type of geometry - are they all points or all polygons...?
    – ian
    17 hours ago










  • Use os.path.join to join paths and filenames together instead of things like this path + '\' + filename
    – BERA
    15 hours ago













up vote
3
down vote

favorite









up vote
3
down vote

favorite











Want to merge all shp files in a folder into one with a new field populated with the source filename. Not getting any errors but not getting any outputs.



Code originally taken from (How to add field with filename when merging shapefiles with ogr2ogr?)



# merge_shps.py
import os
path = "C:TEMPSWS_SUDSCadastral_Maps" # path to your folder of .shp files
merge = "SWS_INSPIRE" # this will be the name of your merged result
directory = os.listdir(path)
count = 0
for filename in directory:
print "n" + filename + "n"
if ".SHP" in filename.upper() and not ".XML" in filename.upper():
# On the first pass, create a clone and add the filename column.
if count == 0:
# Make a clone (matt wilkie)..
cmd = 'ogr2ogr ' + path + '\' + merge + '.shp ' + path + '\' + filename + ' -where "FID < 0"'
print "n" + cmd + "n"
os.system(cmd)
# Add the field (j03lar50n)..
cmd = 'ogrinfo ' + path + '\' + merge + '.shp -sql "ALTER TABLE ' + merge + ' ADD COLUMN filename character(50)"'
print "n" + cmd + "n"
os.system(cmd)
# Now populate the data (capooti)..
print "Merging: " + str(filename)
# You'll need the filename without the .shp extension for the OGR_SQL..
filenameNoExt = filename.replace(".shp","")
cmd = 'ogr2ogr -f "esri shapefile" -update -append "' +
path + '\' + merge + '.shp" "' +
path + '\' + filename +'"'
' -sql "SELECT '' + filename + '' AS filename, * FROM ' + filenameNoExt + '"'
# Uncomment this line to spit the ogr2ogr sentence to the terminal..
print "n" + cmd + "n"
os.system(cmd)
count += 1









share|improve this question









New contributor




Alex Gagnon is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











Want to merge all shp files in a folder into one with a new field populated with the source filename. Not getting any errors but not getting any outputs.



Code originally taken from (How to add field with filename when merging shapefiles with ogr2ogr?)



# merge_shps.py
import os
path = "C:TEMPSWS_SUDSCadastral_Maps" # path to your folder of .shp files
merge = "SWS_INSPIRE" # this will be the name of your merged result
directory = os.listdir(path)
count = 0
for filename in directory:
print "n" + filename + "n"
if ".SHP" in filename.upper() and not ".XML" in filename.upper():
# On the first pass, create a clone and add the filename column.
if count == 0:
# Make a clone (matt wilkie)..
cmd = 'ogr2ogr ' + path + '\' + merge + '.shp ' + path + '\' + filename + ' -where "FID < 0"'
print "n" + cmd + "n"
os.system(cmd)
# Add the field (j03lar50n)..
cmd = 'ogrinfo ' + path + '\' + merge + '.shp -sql "ALTER TABLE ' + merge + ' ADD COLUMN filename character(50)"'
print "n" + cmd + "n"
os.system(cmd)
# Now populate the data (capooti)..
print "Merging: " + str(filename)
# You'll need the filename without the .shp extension for the OGR_SQL..
filenameNoExt = filename.replace(".shp","")
cmd = 'ogr2ogr -f "esri shapefile" -update -append "' +
path + '\' + merge + '.shp" "' +
path + '\' + filename +'"'
' -sql "SELECT '' + filename + '' AS filename, * FROM ' + filenameNoExt + '"'
# Uncomment this line to spit the ogr2ogr sentence to the terminal..
print "n" + cmd + "n"
os.system(cmd)
count += 1






qgis python






share|improve this question









New contributor




Alex Gagnon is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




Alex Gagnon is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited 20 hours ago





















New contributor




Alex Gagnon is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked 20 hours ago









Alex Gagnon

363




363




New contributor




Alex Gagnon is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





Alex Gagnon is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






Alex Gagnon is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












  • Hi Alex, I've had a go at running the code you've posted and it executes without issue. I get a shp file called SWS_INSPIRE in the same folder as the shp files to be merged containing the merged files. Do all of your shp files contain the same type of geometry - are they all points or all polygons...?
    – ian
    17 hours ago










  • Use os.path.join to join paths and filenames together instead of things like this path + '\' + filename
    – BERA
    15 hours ago


















  • Hi Alex, I've had a go at running the code you've posted and it executes without issue. I get a shp file called SWS_INSPIRE in the same folder as the shp files to be merged containing the merged files. Do all of your shp files contain the same type of geometry - are they all points or all polygons...?
    – ian
    17 hours ago










  • Use os.path.join to join paths and filenames together instead of things like this path + '\' + filename
    – BERA
    15 hours ago
















Hi Alex, I've had a go at running the code you've posted and it executes without issue. I get a shp file called SWS_INSPIRE in the same folder as the shp files to be merged containing the merged files. Do all of your shp files contain the same type of geometry - are they all points or all polygons...?
– ian
17 hours ago




Hi Alex, I've had a go at running the code you've posted and it executes without issue. I get a shp file called SWS_INSPIRE in the same folder as the shp files to be merged containing the merged files. Do all of your shp files contain the same type of geometry - are they all points or all polygons...?
– ian
17 hours ago












Use os.path.join to join paths and filenames together instead of things like this path + '\' + filename
– BERA
15 hours ago




Use os.path.join to join paths and filenames together instead of things like this path + '\' + filename
– BERA
15 hours ago










3 Answers
3






active

oldest

votes

















up vote
6
down vote













I'd suggest you rather go with ogr2ogr in a terminal script directly.



In summary (using the syntax from the linked post), to merge all .shp into merged.shp (both in CWD), with the filename (without extension) added as a column, run from within





  • Bash (Linux):



    for file in *.shp
    do
    if [ -f merged.shp ]
    then
    ogr2ogr -f "ESRI Shapefile" merged.shp $file -update -append -dialect "SQLite" -sql "SELECT '${file%.*}' AS filename, * FROM ${file%.*}"
    else
    ogr2ogr -f "ESRI Shapefile" merged.shp $file -dialect "SQLite" -sql "SELECT '${file%.*}' AS filename, * FROM ${file%.*}"
    fi
    done



  • CMD (Windows Command Line):



    for %F in (*.shp) do (
    if not exists merged.shp (
    ogr2ogr -f "ESRI Shapefile" merged.shp %F -dialect "SQLite" -sql "SELECT '%~nF' AS filename, * FROM %~nF"
    ) else (
    ogr2ogr -f "ESRI Shapefile" merged.shp %F -update -append -dialect "SQLite" -sql "SELECT '%~nF' AS filename, * FROM %~nF"
    )
    )





And to add up to this, there's actually no need to catch the non-existing file case, ogr2ogr will (at least in recent versions) create the file even in -append mode:





  • Bash (Linux):



    for file in *.shp
    do
    ogr2ogr -f "ESRI Shapefile" merged.shp $file -dialect "SQLite" -sql "SELECT '${file%.*}' AS filename, * FROM ${file%.*}"
    done



  • CMD (Windows Command Line):



    for %F in (*.shp) do (
    ogr2ogr -f "ESRI Shapefile" merged.shp %F -update -append -dialect "SQLite" -sql "SELECT '%~nF' AS filename, * FROM %~nF"
    )







share|improve this answer






























    up vote
    2
    down vote













    Turns out the path to the ogr2ogr executable wasn't included in my Path environment variable... seems to work now.






    share|improve this answer










    New contributor




    Alex Gagnon is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.

























      up vote
      0
      down vote













      Your question is tagged with qgis so I'm answering with QGIS, even if you show us only code with ogr2ogr.



      In QGIS, you can use the tool Merge vector layers. Two attributes are added automatically, the filename and the filepath.



      Then if you want to do the same in python, you can open the history of Processing commands (from the previous step above with Merge vector layer) and copy/paste the python line.



      It gives:



      processing.run("native:mergevectorlayers", {'LAYERS':['path/to/first/layer','path/to/second/layer'],'CRS':None,'OUTPUT':'memory:'})


      It will create a memory layer.






      share|improve this answer





















        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',
        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
        });


        }
        });






        Alex Gagnon is a new contributor. Be nice, and check out our Code of Conduct.










        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fgis.stackexchange.com%2fquestions%2f306055%2fmerge-all-shp-files-in-a-folder-into-one-with-a-new-field-populated-with-the-sou%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes








        up vote
        6
        down vote













        I'd suggest you rather go with ogr2ogr in a terminal script directly.



        In summary (using the syntax from the linked post), to merge all .shp into merged.shp (both in CWD), with the filename (without extension) added as a column, run from within





        • Bash (Linux):



          for file in *.shp
          do
          if [ -f merged.shp ]
          then
          ogr2ogr -f "ESRI Shapefile" merged.shp $file -update -append -dialect "SQLite" -sql "SELECT '${file%.*}' AS filename, * FROM ${file%.*}"
          else
          ogr2ogr -f "ESRI Shapefile" merged.shp $file -dialect "SQLite" -sql "SELECT '${file%.*}' AS filename, * FROM ${file%.*}"
          fi
          done



        • CMD (Windows Command Line):



          for %F in (*.shp) do (
          if not exists merged.shp (
          ogr2ogr -f "ESRI Shapefile" merged.shp %F -dialect "SQLite" -sql "SELECT '%~nF' AS filename, * FROM %~nF"
          ) else (
          ogr2ogr -f "ESRI Shapefile" merged.shp %F -update -append -dialect "SQLite" -sql "SELECT '%~nF' AS filename, * FROM %~nF"
          )
          )





        And to add up to this, there's actually no need to catch the non-existing file case, ogr2ogr will (at least in recent versions) create the file even in -append mode:





        • Bash (Linux):



          for file in *.shp
          do
          ogr2ogr -f "ESRI Shapefile" merged.shp $file -dialect "SQLite" -sql "SELECT '${file%.*}' AS filename, * FROM ${file%.*}"
          done



        • CMD (Windows Command Line):



          for %F in (*.shp) do (
          ogr2ogr -f "ESRI Shapefile" merged.shp %F -update -append -dialect "SQLite" -sql "SELECT '%~nF' AS filename, * FROM %~nF"
          )







        share|improve this answer



























          up vote
          6
          down vote













          I'd suggest you rather go with ogr2ogr in a terminal script directly.



          In summary (using the syntax from the linked post), to merge all .shp into merged.shp (both in CWD), with the filename (without extension) added as a column, run from within





          • Bash (Linux):



            for file in *.shp
            do
            if [ -f merged.shp ]
            then
            ogr2ogr -f "ESRI Shapefile" merged.shp $file -update -append -dialect "SQLite" -sql "SELECT '${file%.*}' AS filename, * FROM ${file%.*}"
            else
            ogr2ogr -f "ESRI Shapefile" merged.shp $file -dialect "SQLite" -sql "SELECT '${file%.*}' AS filename, * FROM ${file%.*}"
            fi
            done



          • CMD (Windows Command Line):



            for %F in (*.shp) do (
            if not exists merged.shp (
            ogr2ogr -f "ESRI Shapefile" merged.shp %F -dialect "SQLite" -sql "SELECT '%~nF' AS filename, * FROM %~nF"
            ) else (
            ogr2ogr -f "ESRI Shapefile" merged.shp %F -update -append -dialect "SQLite" -sql "SELECT '%~nF' AS filename, * FROM %~nF"
            )
            )





          And to add up to this, there's actually no need to catch the non-existing file case, ogr2ogr will (at least in recent versions) create the file even in -append mode:





          • Bash (Linux):



            for file in *.shp
            do
            ogr2ogr -f "ESRI Shapefile" merged.shp $file -dialect "SQLite" -sql "SELECT '${file%.*}' AS filename, * FROM ${file%.*}"
            done



          • CMD (Windows Command Line):



            for %F in (*.shp) do (
            ogr2ogr -f "ESRI Shapefile" merged.shp %F -update -append -dialect "SQLite" -sql "SELECT '%~nF' AS filename, * FROM %~nF"
            )







          share|improve this answer

























            up vote
            6
            down vote










            up vote
            6
            down vote









            I'd suggest you rather go with ogr2ogr in a terminal script directly.



            In summary (using the syntax from the linked post), to merge all .shp into merged.shp (both in CWD), with the filename (without extension) added as a column, run from within





            • Bash (Linux):



              for file in *.shp
              do
              if [ -f merged.shp ]
              then
              ogr2ogr -f "ESRI Shapefile" merged.shp $file -update -append -dialect "SQLite" -sql "SELECT '${file%.*}' AS filename, * FROM ${file%.*}"
              else
              ogr2ogr -f "ESRI Shapefile" merged.shp $file -dialect "SQLite" -sql "SELECT '${file%.*}' AS filename, * FROM ${file%.*}"
              fi
              done



            • CMD (Windows Command Line):



              for %F in (*.shp) do (
              if not exists merged.shp (
              ogr2ogr -f "ESRI Shapefile" merged.shp %F -dialect "SQLite" -sql "SELECT '%~nF' AS filename, * FROM %~nF"
              ) else (
              ogr2ogr -f "ESRI Shapefile" merged.shp %F -update -append -dialect "SQLite" -sql "SELECT '%~nF' AS filename, * FROM %~nF"
              )
              )





            And to add up to this, there's actually no need to catch the non-existing file case, ogr2ogr will (at least in recent versions) create the file even in -append mode:





            • Bash (Linux):



              for file in *.shp
              do
              ogr2ogr -f "ESRI Shapefile" merged.shp $file -dialect "SQLite" -sql "SELECT '${file%.*}' AS filename, * FROM ${file%.*}"
              done



            • CMD (Windows Command Line):



              for %F in (*.shp) do (
              ogr2ogr -f "ESRI Shapefile" merged.shp %F -update -append -dialect "SQLite" -sql "SELECT '%~nF' AS filename, * FROM %~nF"
              )







            share|improve this answer














            I'd suggest you rather go with ogr2ogr in a terminal script directly.



            In summary (using the syntax from the linked post), to merge all .shp into merged.shp (both in CWD), with the filename (without extension) added as a column, run from within





            • Bash (Linux):



              for file in *.shp
              do
              if [ -f merged.shp ]
              then
              ogr2ogr -f "ESRI Shapefile" merged.shp $file -update -append -dialect "SQLite" -sql "SELECT '${file%.*}' AS filename, * FROM ${file%.*}"
              else
              ogr2ogr -f "ESRI Shapefile" merged.shp $file -dialect "SQLite" -sql "SELECT '${file%.*}' AS filename, * FROM ${file%.*}"
              fi
              done



            • CMD (Windows Command Line):



              for %F in (*.shp) do (
              if not exists merged.shp (
              ogr2ogr -f "ESRI Shapefile" merged.shp %F -dialect "SQLite" -sql "SELECT '%~nF' AS filename, * FROM %~nF"
              ) else (
              ogr2ogr -f "ESRI Shapefile" merged.shp %F -update -append -dialect "SQLite" -sql "SELECT '%~nF' AS filename, * FROM %~nF"
              )
              )





            And to add up to this, there's actually no need to catch the non-existing file case, ogr2ogr will (at least in recent versions) create the file even in -append mode:





            • Bash (Linux):



              for file in *.shp
              do
              ogr2ogr -f "ESRI Shapefile" merged.shp $file -dialect "SQLite" -sql "SELECT '${file%.*}' AS filename, * FROM ${file%.*}"
              done



            • CMD (Windows Command Line):



              for %F in (*.shp) do (
              ogr2ogr -f "ESRI Shapefile" merged.shp %F -update -append -dialect "SQLite" -sql "SELECT '%~nF' AS filename, * FROM %~nF"
              )








            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited 16 hours ago

























            answered 17 hours ago









            ThingumaBob

            5,5481322




            5,5481322
























                up vote
                2
                down vote













                Turns out the path to the ogr2ogr executable wasn't included in my Path environment variable... seems to work now.






                share|improve this answer










                New contributor




                Alex Gagnon is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.






















                  up vote
                  2
                  down vote













                  Turns out the path to the ogr2ogr executable wasn't included in my Path environment variable... seems to work now.






                  share|improve this answer










                  New contributor




                  Alex Gagnon is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                  Check out our Code of Conduct.




















                    up vote
                    2
                    down vote










                    up vote
                    2
                    down vote









                    Turns out the path to the ogr2ogr executable wasn't included in my Path environment variable... seems to work now.






                    share|improve this answer










                    New contributor




                    Alex Gagnon is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                    Check out our Code of Conduct.









                    Turns out the path to the ogr2ogr executable wasn't included in my Path environment variable... seems to work now.







                    share|improve this answer










                    New contributor




                    Alex Gagnon is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                    Check out our Code of Conduct.









                    share|improve this answer



                    share|improve this answer








                    edited 15 hours ago









                    T_Bacon

                    1,925514




                    1,925514






                    New contributor




                    Alex Gagnon is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                    Check out our Code of Conduct.









                    answered 15 hours ago









                    Alex Gagnon

                    363




                    363




                    New contributor




                    Alex Gagnon is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                    Check out our Code of Conduct.





                    New contributor





                    Alex Gagnon is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                    Check out our Code of Conduct.






                    Alex Gagnon is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                    Check out our Code of Conduct.






















                        up vote
                        0
                        down vote













                        Your question is tagged with qgis so I'm answering with QGIS, even if you show us only code with ogr2ogr.



                        In QGIS, you can use the tool Merge vector layers. Two attributes are added automatically, the filename and the filepath.



                        Then if you want to do the same in python, you can open the history of Processing commands (from the previous step above with Merge vector layer) and copy/paste the python line.



                        It gives:



                        processing.run("native:mergevectorlayers", {'LAYERS':['path/to/first/layer','path/to/second/layer'],'CRS':None,'OUTPUT':'memory:'})


                        It will create a memory layer.






                        share|improve this answer

























                          up vote
                          0
                          down vote













                          Your question is tagged with qgis so I'm answering with QGIS, even if you show us only code with ogr2ogr.



                          In QGIS, you can use the tool Merge vector layers. Two attributes are added automatically, the filename and the filepath.



                          Then if you want to do the same in python, you can open the history of Processing commands (from the previous step above with Merge vector layer) and copy/paste the python line.



                          It gives:



                          processing.run("native:mergevectorlayers", {'LAYERS':['path/to/first/layer','path/to/second/layer'],'CRS':None,'OUTPUT':'memory:'})


                          It will create a memory layer.






                          share|improve this answer























                            up vote
                            0
                            down vote










                            up vote
                            0
                            down vote









                            Your question is tagged with qgis so I'm answering with QGIS, even if you show us only code with ogr2ogr.



                            In QGIS, you can use the tool Merge vector layers. Two attributes are added automatically, the filename and the filepath.



                            Then if you want to do the same in python, you can open the history of Processing commands (from the previous step above with Merge vector layer) and copy/paste the python line.



                            It gives:



                            processing.run("native:mergevectorlayers", {'LAYERS':['path/to/first/layer','path/to/second/layer'],'CRS':None,'OUTPUT':'memory:'})


                            It will create a memory layer.






                            share|improve this answer












                            Your question is tagged with qgis so I'm answering with QGIS, even if you show us only code with ogr2ogr.



                            In QGIS, you can use the tool Merge vector layers. Two attributes are added automatically, the filename and the filepath.



                            Then if you want to do the same in python, you can open the history of Processing commands (from the previous step above with Merge vector layer) and copy/paste the python line.



                            It gives:



                            processing.run("native:mergevectorlayers", {'LAYERS':['path/to/first/layer','path/to/second/layer'],'CRS':None,'OUTPUT':'memory:'})


                            It will create a memory layer.







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered 10 hours ago









                            Gustry

                            1,227615




                            1,227615






















                                Alex Gagnon is a new contributor. Be nice, and check out our Code of Conduct.










                                draft saved

                                draft discarded


















                                Alex Gagnon is a new contributor. Be nice, and check out our Code of Conduct.













                                Alex Gagnon is a new contributor. Be nice, and check out our Code of Conduct.












                                Alex Gagnon is a new contributor. Be nice, and check out our Code of Conduct.
















                                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.





                                Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                Please pay close attention to the following guidance:


                                • 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%2f306055%2fmerge-all-shp-files-in-a-folder-into-one-with-a-new-field-populated-with-the-sou%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

                                Plaza Victoria

                                In PowerPoint, is there a keyboard shortcut for bulleted / numbered list?

                                How to put 3 figures in Latex with 2 figures side by side and 1 below these side by side images but in...