这是我在这里的第一个问题,我对python还不熟悉,我正试图找出一些方法来建立一个自动的3D模型处理链,它依赖于存储在JSON文件中的数据从一个服务器移动到另一个服务器。在
问题是我需要将绝对路径存储到正在处理的文件,但是这些绝对路径应该在第一次处理时在原始JSON文件中进行修改。在
基本上JSON文件如下所示:
{
"normaldir": "D:\\Outgoing\\1621_1\\",
"projectdir": "D:\\Outgoing\\1622_2\\"
}
我想将文件路径重命名为
^{pr2}$我一直在尝试使用以下代码替换路径的第一部分,但它不起作用:
def processscan(scanfile):
configfile= MonitorDirectory + scanfile
with open(configfile, 'r+') as file:
content = file.read()
file.seek(0)
content.replace("D:\\Outgoing\\", "X:\\Incoming\\")
file.write(content)
但是这根本不起作用,所以我尝试正确解释JSON文件并替换来自here的密钥代码:
def processscan(scanfile):
configfile= MonitorDirectory + scanfile
with open(configfile, 'r+') as settingsData:
settings = json.load(settingsData)
settings['normaldir'] = 'X:\\Incoming\\1621_1\\'
settings['projectdir'] = 'X:\\Incoming\\1622_2\\'
settingsData.seek(0) # rewind to beginning of file
settingsData.write(json.dumps(settings,indent=2,sort_keys=True)) #write the updated version
settingsData.truncate() #truncate the remainder of the data in the file
这很好地工作,但是我替换了整个路径,所以它不会真正适用于我需要处理的每个JSON文件。我真正想做的是获取一个与文件路径相对应的JSON密钥,保留最后8个字符,并用一个新的字符串替换补丁的其余部分,但我不知道如何在python中使用JSON来实现这一点,就我所知我不能编辑键的一部分。 有人对此有解决办法吗?在
谢谢!在
Python附带一个json库。 通过这个库,您可以读写JSON文件(或JSON字符串)。 解析的数据被转换成Python对象,反之亦然。在
要使用
json
库,只需导入它:假设您的数据存储在
^{pr2}$input_data.json
文件中。在你这样读文件:
或者,或者:
您的数据会自动转换为Python对象,在这里您将得到一个
dict
:注意:我使用的是python2.7,所以您可以得到前缀为“u”的unicode字符串,比如
u'projectdir'
。现在很容易更改
normaldir
和projectdir
的值:由于
obj
是dict
,您还可以使用update
方法,如下所示:这样,您就可以使用类似JSON的语法。在
最后,您可以将Python对象写回JSON文件:
或者,也可以使用缩进:
备注:使用缓冲区(变量
content
)读/写JSON对象更快。替换逻辑失败,因为您需要将内容重新分配给新字符串,
str.replace
不是就地操作,它创建了一个新字符串:使用json方法只需使用当前值进行替换:
^{pr2}$如果您真的想保留最后8个字符并加上一个字符串,您还需要
truncate()
然后使用w重新打开文件并转储/写入新值:.replace
返回一个新字符串,不要更改它。但不应将json文件视为普通文本文件,因此可以将解析json与替换结合起来:相关问题 更多 >
编程相关推荐