在python中,如何编写包含括号和引号的文本文件?
Python初学者在这里,我真的很想打印一个文本文件:在python中,如何编写包含括号和引号的文本文件?,python,variables,text,Python,Variables,Text,Python初学者在这里,我真的很想打印一个文本文件: {"geometry": {"type": "Point", "coordinates": [127.03790738341824,-21.727244054924235]}, "type": "Feature", "properties": {}} 有多个方括号的事实让我感到困惑,在尝试以下操作后,它会抛出语法错误: def test(): f = open('helloworld.txt','w') lat_test
{"geometry": {"type": "Point", "coordinates":
[127.03790738341824,-21.727244054924235]}, "type": "Feature", "properties": {}}
有多个方括号的事实让我感到困惑,在尝试以下操作后,它会抛出语法错误
:
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
非常感谢您的帮助。您传递给
f.write()
的字符串格式不正确。尝试:
f.write('{"geometry": {"type": "Point", "coordinates": [%s, %s]}, "type": "Feature", "properties": {}}' % (lat_test, lon_test))
这将使用单引号作为最外层的引号集,并允许嵌入双引号。此外,您不需要在lat周围使用str()
,只要%s
将为您在其上运行str()
。你的第二个也不正确(你通过了两次lat_测试),我在上面的例子中修复了它
如果您在这里所做的是编写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)
您还可以使用三重引号:
f.write("""{"geometry": {"type": "Point", "coordinates": [%s, %s]}, "type": "Feature", "properties": {}}""" % (str(lat_test), str(lat_test)))
但在这种情况下,json包会起作用。文本文件的格式是否正确?文件的实际格式将是geojson。我想我会把扩展名从txt改成js