-1

I tried something like this and It doesn't work

counter = 0
with open('tmp.txt','a') as file:
    while(counter == 0):
        if file.readline() == "\n":
            file.write("HI")
            file.write("\n")
            counter = 1
            break
        else:
            continue 

Following is the content of the text file.

1
2
3
4

5
6
7
8
9

0

How do I append text to the first occurrence of newline in the file and then add a new line

Tejas
  • 35
  • 1
  • 10
  • Notice that the whole use of `counter` is not necessary. It is the same as just doing `while True` and `break`ing in the `if` (As you do anyway...) – Tomerikoo Aug 26 '21 at 11:13

1 Answers1

3

Don't change the file while reading it. Instead read, change the file and write again:

with open('tmp.txt') as file:
  content = file.read()

new_content = content.replace('\n\n', f'\nHello\n',1)
with open('tmp.txt','w') as file:
  file.write(new_content)
Mohammad
  • 3,276
  • 2
  • 19
  • 35
  • 1
    I like your optimisation there, a good example of why planning before doing is important – Peter Aug 26 '21 at 11:15