首页 > 解决方案 > 删除文件中的第一个字符

问题描述

我正在尝试从包含 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 字符串转储到文件时,字符串被双引号包围。我正在尝试从文件的第一个和最后一个位置删除这些双引号。

标签: pythonjson

解决方案


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

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

考虑以下最小且完整的示例:

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 创建,要么通过 remove json.dumps()which 将对象转换为 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

推荐阅读