I have the following file:
---
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
---
And I need to open it in write mode, traverse it line by line until I find the line I want to change (i.e: pytest summary: 1 failed, 63 passed, 32 warnings in 8.72s), and then change that line to read "pytest summary: 1 failed, 63 passed, 32 warnings in 8.72 seconds", thus modifying the file. Also, if it finds a line that is already in the right format, (i.e: pytest summary: 28 passed, 28 warnings in 5.16 seconds) ignore it and keep looking for the lines that need to be modified.
Here's my regex to modify the lines: re.sub(r"(\b\d+\.\d+)[a-z]", r"\1 seconds", file_name) #substitutes "8.13s" for "8.13 seconds"
I'm new to python and don't know how to perform modifications to a file. Could someone show me how to do it using file.read()/write()?
I've tried this code but it doesn't work at all:
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)
Expected output (not happening ; file remains unchanged just like above):
---
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
---