2017-10-07 50 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包完成了这项工作。

相关问题