python - 删除文件中的第一个字符
问题描述
我正在尝试从包含 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 字符串转储到文件时,字符串被双引号包围。我正在尝试从文件的第一个和最后一个位置删除这些双引号。
解决方案
如果您已有 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
推荐阅读
- javascript - 如何在 onClick 事件 Nextjs 中暂停/启动 GSAP 动画
- javascript - 在 R Shiny 中,当链中的对象被隐藏时,如何维护反应链?
- android - android 设备上的色调和背景显示不同的颜色
- node.js - MongoDB:如何 1. 锁定集合 2. 读取 3. 基于读取的写入?
- flutter - 我可以在 Flutter Flame 中使用 Widget 作为实际组件吗
- python - Numpy Matrix 删除等于数组的行
- css - TailwindCSS 暗模式莫名其妙的行为
- google-sheets - 使用 IMPORTRANGE 从具有动态单元格引用的工作表中获取数据
- c++ - 为什么编译时执行比运行时执行快得多?
- sql - 与 group by 进行内部连接并查找列中重复值的计数