python替换文件中不起作用的行

2024-06-16 12:17:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个名为myBlock.json文件地址:

{
  "server": "https://abc.us",
  "name":"XYZ",
  "myData":"2019-04-08T15:43:05.810483Z",
  "someFlg":"T",
  "moreData":"k"
}

我正在尝试用新的日期和时间信息来改变这一点

        with open("myBlock.json") as json_data:
            self.myBlockInfo = json.load(json_data)

        origData = self.myBlockInfo["myData"]
        origLine = '\"myData\":\"'+origData +'\",'

        nowData = self.timeISO8601ZuluUTC()
        newLine = '\"myData\":\"'+nowData+'\",'

        with open("myBlock.json", "r+") as fh:
            for line in fh.readlines():
                if origLine in line:
                    print ("1-->", line)
                    str.replace(line, origLine, newLine)
                    print("2-->", line)

但不仅行是一样的,而且文件也是一样的myBlock.Json文件保持不变而不变?你知道吗


Tags: 文件selfjsondataaswithlinenewline
3条回答

您可以通过以下方式编辑文件:

with open("myBlock.json", encoding="utf-8") as json_data:
    myBlockInfo = json.load(json_data)

origData = myBlockInfo["myData"]
origLine = '\"myData\":\"'+origData +'\",'

nowData = "asdsa"
newLine = '\"myData\":\"'+nowData+'\",'
myBlockInfo["myData"] = "sdfsd"
updated =  open("myBlock.json", "w", encoding="utf-8")
json.dump(myBlockInfo, updated)

直接编辑myBlockInfo["myData"]块并用json.dump文件. 另外,您可以使用encoding选项来确保读取和写入时的两种编码相同

你要找的是[Python 3]: json.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)的缩进:

If indent is a non-negative integer or string, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0, negative, or "" will only insert newlines. None (the default) selects the most compact representation. Using a positive integer indent indents that many spaces per level. If indent is a string (such as "\t"), that string is used to indent each level.

代码.py

#!/usr/bin/env python3

import sys
import json


def main(argv):
    with open("in.json") as inf:
        obj = json.load(inf)

    print("Original date:", obj["myData"])
    # Modify obj["myData"] to whatever you need (self.timeISO8601ZuluUTC())

    output_indent = int(argv[0]) if len(argv) and argv[0].isdecimal() else None
    with open("out.json", "w") as outf:
        json.dump(obj, outf, indent=output_indent)


if __name__ == "__main__":
    print("Python {:s} on {:s}\n".format(sys.version, sys.platform))
    main(sys.argv[1:])
    print("Done.")

输出

[cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q055578224]> sopr.bat
*** Set shorter prompt to better fit when pasted in StackOverflow (or other) pages ***

[prompt]> dir /b
code.py
in.json

[prompt]> type in.json
{
  "server": "https://abc.us",
  "name":"XYZ",
  "myData":"2019-04-08T15:43:05.810483Z",
  "someFlg":"T",
  "moreData":"k"
}

[prompt]> "e:\Work\Dev\VEnvs\py_064_03.07.03_test0\Scripts\python.exe" code.py
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] on win32

Original date: 2019-04-08T15:43:05.810483Z
Done.

[prompt]> dir /b
code.py
in.json
out.json

[prompt]> type out.json
{"server": "https://abc.us", "name": "XYZ", "myData": "2019-04-08T15:43:05.810483Z", "someFlg": "T", "moreData": "k"}
[prompt]>
[prompt]> "e:\Work\Dev\VEnvs\py_064_03.07.03_test0\Scripts\python.exe" code.py 2
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] on win32

Original date: 2019-04-08T15:43:05.810483Z
Done.

[prompt]> dir /b
code.py
in.json
out.json

[prompt]> type out.json
{
  "server": "https://abc.us",
  "name": "XYZ",
  "myData": "2019-04-08T15:43:05.810483Z",
  "someFlg": "T",
  "moreData": "k"
}

如您所见,该文件已被很好地重写,而无需修改其原始(文本)内容。你知道吗

首先,不需要在单引号内转义双引号。我是说,用这个来代替:

origLine = '"myData":"'+origData +'",'

然后,更简单的替换方法是替换整个文件内容,而不是逐行读取:

with open("myBlock.json", "r") as fh:
    oldcontent = fh.read()
    if origLine in oldcontent:
        print("found!!")
    newcontent = oldcontent.replace(origLine, newLine)
with open("newfile.json", "w") as fh:
    fh.write(newcontent)

但是,这并不能保证有效!我在第一个if块中放置了一个with,以帮助您检查所期望的内容是否真的存在。输入JSON可能在冒号周围有空格,比如"myData": "foobar",甚至在冒号周围有新行。这些都是合法的JSON。这就是为什么评论中有人建议您阅读JSON,修改它,然后写回JSON。你知道吗

如果你认为回写JSON会弄乱格式,试试看

 newcontent = json.dumps(modified_data, indent=4)

indent=4将通过插入适当的缩进来“漂亮地打印”您的JSON,可能会保留一些您期望的格式。你知道吗

相关问题 更多 >