删除文件中的第一个字符

时间:2019-09-24 18:53:36

标签: python json

我正在尝试从包含JSON字符串的文件中删除第一个字符(“)。为此,我使用Python。下面是我的代码:

jsonOutput = 'JsonString_{}.{}'.format(str(uuid.uuid1()), "json")
jsonOutput_File = os.path.join(arcpy.env.scratchFolder, jsonOutput)

with open(jsonOutput_File, 'w') as json_file:
    json.dump(jsonString, json_file)

// I was able to remove the very last character using the code below
with open(jsonOutput_File, 'r+') as read_json_file:
    read_json_file.seek(-1, os.SEEK_END)
    read_json_file.truncate()

基本上,当我将JSON字符串转储到文件中时,字符串被双引号引起来。我正在尝试从文件的第一个和最后一个位置删除这些双引号。

1 个答案:

答案 0 :(得分:0)

如果您已经有了JSON字符串,只需将其写入文件即可。

使用json.dump()将JSON字符串再次编码为JSON是一个坏主意,并且不会像删除前导和尾随引号一样简单地解决。

请考虑以下最小和完整示例:

import json
import os
import uuid

myobject = {"hello": "world"}
jsonString = json.dumps(myobject)
jsonOutput = 'JsonString_{}.{}'.format(str(uuid.uuid1()), "json")
jsonOutput_File = os.path.join("d:\\", jsonOutput)
with open(jsonOutput_File, 'w') as json_file:
    json.dump(jsonString, json_file)

输出是一个包含以下内容的文件:

"{\"hello\": \"world\"}"

删除引号将使其成为有效的JSON。

相反,请避免重复创建JSON,方法是删除json.dumps()一次将对象转换为JSON,或者删除json.dump()再次进行。

解决方案1:

import json
import os
import uuid

myobject = {"hello": "world"}
                                          # <-- deleted line here
jsonOutput = 'JsonString_{}.{}'.format(str(uuid.uuid1()), "json")
jsonOutput_File = os.path.join("d:\\", jsonOutput)
with open(jsonOutput_File, 'w') as json_file:
    json.dump(myobject, json_file)        # <-- changed to object here

解决方案2:

import json
import os
import uuid

myobject = {"hello": "world"}
jsonString = json.dumps(myobject)
jsonOutput = 'JsonString_{}.{}'.format(str(uuid.uuid1()), "json")
jsonOutput_File = os.path.join("d:\\", jsonOutput)
with open(jsonOutput_File, 'w') as json_file:
    json_file.write(jsonString)                # <-- Note this line