33import gzip
44import shutil
55import subprocess
6+ import tempfile
7+ from pathlib import Path
68
79from osgeo import ogr , osr
810
@@ -14,52 +16,51 @@ def gzipped_csv_to_gzipped_geojson(
1416 geometry_field : str = "geom" ,
1517 add_metadata : bool = False
1618):
17- """Use ogr2ogr to convert csv file to GeoJSON.
19+ """Convert gzipped csv file to gzipped GeoJSON.
1820
19- Check if file is compressed.
21+ First the gzipped files are unzipped and stored in temporary csv and geojson files.
22+ Then the unzipped csv file is converted into a geojson file with ogr2ogr.
23+ Last, the generated geojson file is again compressed using gzip.
2024 """
21- csv_file = "temp.csv"
22- geojson_file = "temp.geojson"
25+ # generate tempory files which will be automatically deleted at the end
26+ tmp_csv_file = os .path .join (tempfile ._get_default_tempdir (), 'tmp.csv' )
27+ tmp_geojson_file = os .path .join (tempfile ._get_default_tempdir (), 'tmp.geojson' )
28+
2329 outfile = filename .replace (".csv" , f"_{ geometry_field } .geojson" )
24- filename_without_path = csv_file .split ("/" )[- 1 ].replace (".csv" , "" )
2530
31+ # uncompress content of zipped csv file and save to csv file
2632 with gzip .open (filename , 'rb' ) as f_in :
27- with open (csv_file , 'wb' ) as f_out :
33+ with open (tmp_csv_file , "wb" ) as f_out :
2834 shutil .copyfileobj (f_in , f_out )
2935
30- # need to remove file here because ogr2ogr can't overwrite when choosing GeoJSON
31- if os .path .isfile (geojson_file ):
32- os .remove (geojson_file )
33-
36+ # use ogr2ogr to transform csv file into geojson file
3437 # TODO: remove geom column from normal attributes in sql query
3538 subprocess .run (
3639 [
3740 "ogr2ogr" ,
3841 "-f" ,
3942 "GeoJSON" ,
40- geojson_file ,
41- csv_file ,
43+ tmp_geojson_file ,
44+ tmp_csv_file ,
4245 "-sql" ,
43- f'SELECT *, CAST({ geometry_field } as geometry) FROM "{ filename_without_path } "' , # noqa E501
46+ f'SELECT *, CAST({ geometry_field } as geometry) FROM "tmp "' , # noqa E501
4447 ],
4548 check = True ,
4649 )
47- logger .info (f"converted { filename } to { outfile } ." )
4850
4951 if add_metadata :
50- add_metadata_to_geojson (geojson_file )
52+ add_metadata_to_geojson (tmp_geojson_file )
5153
52- cast_datatypes_for_geojson (geojson_file )
54+ cast_datatypes_for_geojson (tmp_geojson_file )
5355
54- with open (geojson_file , "r" ) as f :
56+ # compress geojson file with gzip
57+ with open (tmp_geojson_file , "r" ) as f :
5558 json_data = json .load (f )
5659
5760 with gzip .open (outfile , 'wt' ) as fout :
5861 json .dump (json_data , fout )
5962
60- # remove temp files
61- os .remove (csv_file )
62- os .remove (geojson_file )
63+ logger .info (f"converted { filename } to { outfile } with ogr2ogr." )
6364
6465
6566def csv_to_geojson (filename : str , geometry_field : str = "geom" ):
0 commit comments