0

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
---
user15278135
  • 111
  • 8
  • What is the actual output? – ewokx May 07 '21 at 07:39
  • The file is unchanged by my code so there are no modifications made. The actual output is the first block of text in the question @ewong – user15278135 May 07 '21 at 07:42
  • Does this answer your question? [Is it possible to modify lines in a file in-place?](https://stackoverflow.com/questions/5453267/is-it-possible-to-modify-lines-in-a-file-in-place) – Adrian W May 07 '21 at 15:34

1 Answers1

1

re.sub() returns the changed string. file_contents remains the same.

Try:

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)
ewokx
  • 2,204
  • 3
  • 14
  • 27