简体   繁体   中英

How to Import multiple csv files into QGIS 3.22.2?

I want to import multiple csv files at once into QGIS. The files have Lat/Long data. I want the files to project the points. Basically I want the same results from importing the csv files as I would if I used Data Source Manager-Delimited Text with Point Coordinates selected and the x-field and y-field set to Long/Lat respectively.

I keep coming across the same python code on numerous forums. While I can get the files to import as tables, I can not get them to load with geometry (a next stage problem will also be getting the timestamp to load as date instead of a string, I may have to refactor all the files).

Here's the code available on forums which results in loading broken links (my files have column headers "Lat" and "Long"):

import glob, os

# Define path to  directory of your csv files
path_to_csv = "C:/File Path/"

# Set current directory to path of csv files
os.chdir(path_to_csv)  
# Find each .csv file and load them as vector layers
for fname in glob.glob("*.csv"):  
    uri ="file:///"+path_to_csv + fname+"encoding=%s&delimiter=%s&xField=%s&yField=%s&crs=%s" % ("UTF-8",",", "Long", "Lat","epsg:4326")
    name=fname.replace('.csv', '')
    lyr = QgsVectorLayer(uri, name, 'delimitedtext')
    QgsProject.instance().addMapLayer(lyr)

This code will load layers, but with a warning triangle for "Unavailable Layer". Clicking on the triangle opens the "Repair Data Source" window. I can manually select the file and repair the link. But then it is nothing more than a table with all fields as strings.

If I run the code like this I get the files to import, but only as tables and without geometry:

import glob, os

# Define path to  directory of your csv files
path_to_csv = "C:/Users/DanielStevens/Documents/Afghanistan Monitoring/Phase 2/Border Crossing/Crossing Polygons/Pakistan/"

# Set current directory to path of csv files
os.chdir(path_to_csv)  
# Find each .csv file and load them as vector layers
for fname in glob.glob("*.csv"):  
    uri ="file:///"+path_to_csv + fname
    "encoding=%s&delimiter=%s&xField=%s&yField=%s&crs=%s" % ("UTF-8",",", "Long", 
    "Lat","epsg:4326")
    name=fname.replace('.csv', '')
    lyr = QgsVectorLayer(uri, name, 'delimitedtext')
    QgsProject.instance().addMapLayer(lyr)

How do I get the CSV files to batch import with geometry (Lat Long projecting points)?

I modified what you had to the line below and it worked perfectly. I removed the encoding because my data wasn't UTF-8. Not sure if that's what did it.

uri = "file:///" + path_to_csv + fname + "?delimiter=%s&crs=epsg:3857&xField=%s&yField=%s" % (",", "lon", "lat")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM