簡體   English   中英

在python中,如何編寫包含布雷克特和引號的文本文件?

[英]In python, how do you write a text file that contains brakets and quotes?

Python初學者在這里,我真的很想處理要打印的文本文件:

{"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

提前非常感謝您的幫助。

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

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

這使用單引號作為最外面的引號集,並允許嵌入雙引號。 另外,您不需要在lat周圍使用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)

您還可以使用三重引用:

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

但是在這種特定情況下,json包可以完成這項工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM