-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.py
More file actions
78 lines (61 loc) · 2.72 KB
/
script.py
File metadata and controls
78 lines (61 loc) · 2.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# an example script for converting coordinates in a csv file
# first clone the coordinates parser repo to your own machine
# create a new project directory for your own project (different to the parser repo), and copy this file there
# change the parameters below and then run your script on the command line with `python script.py`
from os import path
import csv, re, sys
sys.path.append(r'the full path of the coordinates parser repo on your machine')
from converter import convert
# change these parameters before running the script
file_location = r'your file directory'
file_name = 'your file name with .csv on the end'
latitude_field = 'your latitude field in the file'
longitude_field = 'your longitude field in the file'
##### SCRIPT #####
convert_count = 0
errs = 0
records = []
print('converting coordinates in file')
with open(path.join(file_location, file_name), mode = 'r', encoding="utf-8", errors="ignore") as f:
reader = csv.DictReader(f)
for row in reader:
if latitude_field not in row or longitude_field not in row:
print('Please check coordinate field names in your file')
exit()
records.append(row) # we keep them all
converted = None
row["decimalLatitude"] = None
row["decimalLongitude"] = None
if (row[latitude_field] and not row[longitude_field]) or (row[longitude_field] and not row[latitude_field]):
row["decimalLatitude"] = 'error'
row["decimalLongitude"] = 'error'
continue
if not row[latitude_field] and not row[longitude_field]:
continue # nothing needed
# otherwise...
try:
converted = convert(row[latitude_field] + ', ' + row[longitude_field])
except:
errs += 1
row["decimalLatitude"] = 'error'
row["decimalLongitude"] = 'error'
if converted:
row["decimalLatitude"] = converted.decimal_latitude
row["decimalLongitude"] = converted.decimal_longitude
convert_count += 1
#feedback
print()
if convert_count > 0:
print("writing out results file")
field_names = records[0].keys()
newfile = re.sub(r"\.csv$", "_converted.csv", file_name, flags=re.I)
with open(path.join(file_location, newfile), mode='w', newline='', encoding='utf-8') as csv_file:
writer = csv.DictWriter(csv_file, fieldnames=field_names)
writer.writeheader()
writer.writerows(records)
print("Successfully converted coordinates for", convert_count, "rows")
if errs > 0:
print("There were errors converting coordinates for", errs, "rows")
print('See the output file')
else:
print("Coordinates could not be converted for this file")