0

I would like to write an new line and string after the first the first occurrence of a string in Python For example my text file is like:

123456
example string<random>
asdfg
zxc
example string<random>

I would like it to change to

123456
example string<random>
Python inputted string
asdfg
zxc
example string<random> <- Stays the same
  • I think maybe it could be useful if you could mention the bigger picture of what you're trying to achieve here. The task seems oddly specific that maybe there's a better way of doing it – sshashank124 Apr 07 '18 at 14:51
  • `mutable_seq = list(string); mutable_seq.insert(mutable_seq.index(pattern) + 1, 'inserted string'); new_string = ''.join(mutable_seq)` – mental Apr 07 '18 at 14:56
  • Its to inject code after the first function –  Apr 07 '18 at 14:57

1 Answers1

1

read lines from file

lines = []
with open(file_name, 'r') as f:
  for line in f:
    lines.append(line)

with open(file_name, 'w+') as f:
  flag = True
  for line in lines:
    f.write(line)
    if line.startswith("example string") and flag:
      f.write("what ever\n")
      flag = False

input file

123456
example string<random>
asdfg
zxc
example string<random>

output file

123456
example string<random>
what ever
asdfg
zxc
example string<random>
shahaf
  • 4,750
  • 2
  • 29
  • 32