簡體   English   中英

如何在 PYTHON 中打開文件並使用正則表達式修改其內容以查找/匹配/替換模式

[英]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 摘要:1失敗,63通過,32警告在8.72s內),然后將該行更改為讀取“pytest 摘要:1 次失敗,63 次通過,32 次警告在 8.72 秒內”,從而修改文件。 此外,如果它發現一行已經采用正確的格式(即:pytest 摘要:28 次通過,28 次警告在 5.16 秒內)忽略它並繼續尋找需要修改的行。

這是我修改行的正則表達式: re.sub(r"(\b\d+\.\d+)[az]", r"\1 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"\1 seconds", file_contents)  #substitutes 8.13s for 8.13 seconds
    file.seek(0)
    file.truncate()
    file.write(file_contents)

預期的 output (沒有發生;文件保持不變,就像上面一樣):

---
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()返回更改后的字符串。 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"\1 seconds", file_contents)  #substitutes 8.13s for 8.13 seconds
    file.seek(0)
    file.truncate()
    file.write(new_contents)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM