[英]In python, how do you write a text file that contains brakets and quotes?
Python beginner here, I am really struggling with a text file I want to print: Python初学者在这里,我真的很想处理要打印的文本文件:
{"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: 有多个括号的事实使我感到困惑,尝试此操作后会引发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()
As you can see, I have my own variable for latitude and longitude, but python is throwing a syntax error: 如您所见,我有自己的纬度和经度变量,但是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
Thanks a lot in advance for any help. 提前非常感谢您的帮助。
The string you're passing to f.write()
isn't formatted correctly. 您传递给f.write()
的字符串格式不正确。 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. 另外,您不需要在lat周围使用str()
,只要%s
为您在其上运行str()
。 You're second one was incorrect too (you passed lat_test twice), and I fixed it in the example above. 您的第二个也是错误的(您两次通过lat_test),我在上面的示例中修复了它。
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: 如果您在这里编写的是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)
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. 但是在这种特定情况下,json包可以完成这项工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.