0

Python beginner here, I am really struggling with a text file I want to print:

{"geometry": {"type": "Point", "coordinates": 
[127.03790738341824,-21.727244054924235]}, "type": "Feature", "properties": {}}

The fact that has multiple brackets confused me and it throws Syntax Error after trying this:

def test():
    f = open('helloworld.txt','w')
    lat_test = vehicle.location.global_relative_frame.lat
    lon_test = vehicle.location.global_relative_frame.lon
    f.write("{"geometry": {"type": "Point", "coordinates": [%s, %s]}, "type": "Feature", "properties": {}}" % (str(lat_test), str(lat_test)))
    f.close()

As you can see, I have my own variable for latitude and longitude, but python is throwing a syntax error:

File "hello.py", line 90
f.write("{"geometry": {"type": "Point", "coordinates": [%s, %s]}, "type": 
"Feature"" % (str(lat_test), str(lat_test)))
                  ^
SyntaxError: invalid syntax

Thanks a lot in advance for any help.

Ahmad Taha
  • 1,975
  • 2
  • 17
  • 27
diamondx
  • 153
  • 1
  • 6

2 Answers2

1

The string you're passing to f.write() isn't formatted correctly. Try:

f.write('{"geometry": {"type": "Point", "coordinates": [%s, %s]}, "type": "Feature", "properties": {}}' % (lat_test, lon_test))

This uses the single quote as the outermost set of quotes and allows embedding of double quotes. Also, you don't need the str() around the lat and long as %s will run str() on it for you. You're second one was incorrect too (you passed lat_test twice), and I fixed it in the example above.

If what you're doing here is writing JSON, it could be useful to use Python's JSON module to help convert a Python dictionary into a JSON one:

import json

lat_test = vehicle.location.global_relative_frame.lat
lon_test = vehicle.location.global_relative_frame.lon

d = {
    'Geometry': {
        'type': 'Point',
        'coordinates': [lat_test, lon_test],
        'type': 'Feature',
        'properties': {},
    },
}

with open('helloworld.json', 'w') as f:
    json.dump(d, f)
John Szakmeister
  • 44,691
  • 9
  • 89
  • 79
0

You can also use a tripple quote:

f.write("""{"geometry": {"type": "Point", "coordinates": [%s, %s]}, "type": "Feature", "properties": {}}""" % (str(lat_test), str(lat_test)))

But in this specific case json package does the job.