0

I am doing a project and in it I have to frequently edit a file from the position somewhere in the center. I want to go to the 2 characters left to the position from where the word 'rules' starts.

I have tried something like this:

with open("file.txt", "r+") as fh:
    content = fh.read()
    index = content.seek("rules") - 2

But it takes me to the two lines up instead of taking to two characters back.

This is how the file look:

rule1
rule2
rule3
rule4
.
.
.
.
rule100

rules are very good.

So, basically it is the last line of the file which starts with 'rules' and I want to go at the end of the line that is starting with 'rule100' and write a new line that will be something 'rule101' and save the file.

snakecharmerb
  • 47,570
  • 11
  • 100
  • 153
Khubaib Khawar
  • 51
  • 1
  • 11

2 Answers2

1

We'll firstly split the file into lines. - then we'll find the index where "rules" from the list.
From there - we'll insert the new rule we wish to insert.

Then join this list as updated_content.

We then seek to the beginning of the file and write it with updated_content

with open("text.txt", "r+") as fh:
    content = fh.read().splitlines()

    rulesIndex = content.index("rules are very good.")
    content.insert(rulesIndex - 1, "rule101")

    updated_content = "\n".join(content)

    fh.seek(0)
    fh.write(updated_content)

before

rule1
rule2
rule3
rule4
.
.
.
.
rule100

rules are very good.

after

rule1
rule2
rule3
rule4
.
.
.
.
rule100
rule101

rules are very good.
Denis Tsoi
  • 9,428
  • 8
  • 37
  • 56
1

If you only add content to the file you could use append. Then you won't need a special line and search for it. Just do:

with open("file.txt", "a") as fh:
    fh.append("rule101")
Banana
  • 2,295
  • 1
  • 8
  • 25