如何在 PYTHON 中打开文件并使用正则表达式将其内容修改为 find/match/substitute 模式

How to open a file in PYTHON and modify its contents using regex to find/match/substitute patterns

我有以下文件:

---
Proj: pgm1
Status: success
summary:  17 passed, 17 warnings in 18.73s
---
Proj: pgm2
Status: success
summary:  28 passed, 28 warnings in 5.16s
---
Proj: pgm3
Status: failed
summary:  1 failed, 63 passed, 32 warnings in 8.72s
---

并且我需要以写入模式打开它,逐行遍历直到找到我要更改的行(即:pytest summary: 1 failed, 63 passed, 32 warnings in 8.72s),然后将该行更改为“pytest 摘要:1 次失败,63 次通过,8.72 秒内 32 次警告”,从而修改文件。此外,如果它发现一行已经是正确的格式,(即:pytest summary: 28 passed, 28 warnings in 5.16 seconds)忽略它并继续寻找需要修改的行。

这是我修改行的正则表达式:re.sub(r"(\b\d+\.\d+)[a-z]", r" seconds", file_name) #substitutes "8.13s" for "8.13 seconds"

我是 python 的新手,不知道如何对文件进行修改。有人可以告诉我如何使用 file.read()/write() 吗?

我试过这段代码,但它根本不起作用:

with open(file_path, "r+") as file:
    # read the file contents
    file_contents = file.read()
    re.sub(r"(\b\d+\.\d+)[a-z]", r" seconds", file_contents)  #substitutes 8.13s for 8.13 seconds
    file.seek(0)
    file.truncate()
    file.write(file_contents)

预期输出(没有发生;文件与上面一样保持不变):

---
Proj: pgm1
Status: success
summary:  17 passed, 17 warnings in 18.73 seconds
---
Proj: pgm2
Status: success
summary:  28 passed, 28 warnings in 5.16 seconds
---
Proj: pgm3
Status: failed
summary:  1 failed, 63 passed, 32 warnings in 8.72 seconds
---

re.sub() returns 更改后的字符串。 file_contents保持不变。

尝试:

with open(file_path, "r+") as file:
    # read the file contents
    file_contents = file.read()
    new_contents = re.sub(r"(\b\d+\.\d+)[a-z]", r" seconds", file_contents)  #substitutes 8.13s for 8.13 seconds
    file.seek(0)
    file.truncate()
    file.write(new_contents)