2017-10-07 51 views
0
這裏

Python的初學者,我真的有一個文本文件中掙扎我要打印:在python中,你如何編寫一個包含brakets和引號的文本文件?

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

具有多個括號讓我感到困惑的事實,並嘗試此方法後拋出Syntax Error

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() 

由於你可以看到,我有我自己的經度和緯度變量,但python是拋出一個語法錯誤:

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

謝謝提前有很多的幫助。

+0

您的文本文件是[JSON](http://www.json.org/)格式嗎? –

+1

https://stackoverflow.com/a/12309296/5538805 – MrPyCharm

+0

該文件的實際格式將是geojson。我想我只是將擴展名從txt更改爲js – Diamondx

回答

1

傳遞給f.write()的字符串格式不正確。請嘗試:

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

它使用單引號作爲最外面的引號集並允許嵌入雙引號。此外,你不需要str()左右,只要%s就會爲你運行str()。你是第二個也是不正確的(你通過lat_test兩次),我在上面的例子中修復了它。

如果你在這裏做什麼是寫JSON,也可能是使用Python的JSON模塊來轉換一個Python字典成JSON一個有用:

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) 
+0

非常感謝這對我有用! – Diamondx

0

你也可以使用一個特里普爾報價:

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

但是在這個特定情況下,json包完成了這項工作。

相關問題