Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 删除文件中的第一个字符_Python_Json - Fatal编程技术网

Python 删除文件中的第一个字符

Python 删除文件中的第一个字符,python,json,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(jso

我正在尝试从包含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.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的
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
导入json
导入操作系统
导入uuid
myobject={“你好”:“世界”}

#成功了。谢谢@Thomas。我刚刚用.write将我的JSON字符串写入文件。也谢谢你的解释。:@LegendKiller:如果这个解决方案适合你,请勾选这个答案左上角的复选标记,以便其他人知道问题已经解决。谢谢。
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