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

时间:2019-04-08 16:53:59

标签: python replace

我有一个名为myBlock.json的JSON文件:

ERROR in ./src/app-bundle/Resources/js/vue/components/App.vue
Module parse failed: /Users/malikperang/dev_tripfez/tripfez-vm/docker/app/tripfez_web/src/app-bundle/Resources/js/vue/components/App.vue Unexpected token (1:0)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (1:0)
    at Parser.pp$4.raise (/Users/malikperang/dev_tripfez/tripfez-vm/docker/app/tripfez_web/node_modules/acorn/dist/acorn.js:2221:15)
    at Parser.pp.unexpected (/Users/malikperang/dev_tripfez/tripfez-vm/docker/app/tripfez_web/node_modules/acorn/dist/acorn.js:603:10)
    at Parser.pp$3.parseExprAtom (/Users/malikperang/dev_tripfez/tripfez-vm/docker/app/tripfez_web/node_modules/acorn/dist/acorn.js:1822:12)
    at Parser.pp$3.parseExprSubscripts (/Users/malikperang/dev_tripfez/tripfez-vm/docker/app/tripfez_web/node_modules/acorn/dist/acorn.js:1715:21)
    at Parser.pp$3.parseMaybeUnary (/Users/malikperang/dev_tripfez/tripfez-vm/docker/app/tripfez_web/node_modules/acorn/dist/acorn.js:1692:19)
    at Parser.pp$3.parseExprOps (/Users/malikperang/dev_tripfez/tripfez-vm/docker/app/tripfez_web/node_modules/acorn/dist/acorn.js:1637:21)
    at Parser.pp$3.parseMaybeConditional (/Users/malikperang/dev_tripfez/tripfez-vm/docker/app/tripfez_web/node_modules/acorn/dist/acorn.js:1620:21)
    at Parser.pp$3.parseMaybeAssign (/Users/malikperang/dev_tripfez/tripfez-vm/docker/app/tripfez_web/node_modules/acorn/dist/acorn.js:1597:21)
    at Parser.pp$3.parseExpression (/Users/malikperang/dev_tripfez/tripfez-vm/docker/app/tripfez_web/node_modules/acorn/dist/acorn.js:1573:21)
    at Parser.pp$1.parseStatement (/Users/malikperang/dev_tripfez/tripfez-vm/docker/app/tripfez_web/node_modules/acorn/dist/acorn.js:727:47)
    at Parser.pp$1.parseTopLevel (/Users/malikperang/dev_tripfez/tripfez-vm/docker/app/tripfez_web/node_modules/acorn/dist/acorn.js:638:25)
    at Parser.parse (/Users/malikperang/dev_tripfez/tripfez-vm/docker/app/tripfez_web/node_modules/acorn/dist/acorn.js:516:17)
    at Object.parse (/Users/malikperang/dev_tripfez/tripfez-vm/docker/app/tripfez_web/node_modules/acorn/dist/acorn.js:3098:39)
    at Parser.parse (/Users/malikperang/dev_tripfez/tripfez-vm/docker/app/tripfez_web/node_modules/webpack/lib/Parser.js:902:15)
    at NormalModule.<anonymous> (/Users/malikperang/dev_tripfez/tripfez-vm/docker/app/tripfez_web/node_modules/webpack/lib/NormalModule.js:104:16)
    at NormalModule.onModuleBuild (/Users/malikperang/dev_tripfez/tripfez-vm/docker/app/tripfez_web/node_modules/webpack-core/lib/NormalModuleMixin.js:310:10)
    at nextLoader (/Users/malikperang/dev_tripfez/tripfez-vm/docker/app/tripfez_web/node_modules/webpack-core/lib/NormalModuleMixin.js:275:25)
    at /Users/malikperang/dev_tripfez/tripfez-vm/docker/app/tripfez_web/node_modules/webpack-core/lib/NormalModuleMixin.js:259:5
    at Storage.finished (/Users/malikperang/dev_tripfez/tripfez-vm/docker/app/tripfez_web/node_modules/enhanced-resolve/lib/CachedInputFileSystem.js:38:16)
    at /Users/malikperang/dev_tripfez/tripfez-vm/docker/app/tripfez_web/node_modules/graceful-fs/graceful-fs.js:90:16
    at FSReqCallback.readFileAfterClose [as oncomplete] (internal/fs/read_file_context.js:54:3)
 @ ./src/app-bundle/Resources/js/vue/app.js 11:11-42

我正在尝试使用新的日期和时间信息来更改它

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

但不仅行是相同的,而且文件myBlock.Json也保持不变并且没有变化?

3 个答案:

答案 0 :(得分:0)

首先,您不需要在单引号内转义双引号。我的意思是,改用它:

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,可能会保留您期望的某些格式。

答案 1 :(得分:0)

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

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保存文件。另外,您可以使用编码选项来确保读写时的两种编码相同

答案 2 :(得分:0)

您要查找的是[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)中的 indent kwarg

  

如果 indent 是非负整数或字符串,则JSON数组元素和对象成员将以该缩进级别进行漂亮打印。缩进级别0,负数或""将仅插入换行符。 None(默认)选择最紧凑的表示形式。使用正整数缩进会使每个级别缩进多个空格。如果 indent 是字符串(例如"\t"),则该字符串用于缩进每个级别。

code.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"
}

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