-2
    f= open('elk.in','r')
lines = f.readlines()
for line in lines:
    if line.startswith('vkloff'):
        p=lines.index(line)+1
        #print(lines[p])
        break
lines[p] = f'{string}\n'
string=''
with open('elk.in','w') as out:
    out.writelines(lines)
out.close()

Here in lines[p] if I remove \n the lines below it get removed. How does it work then?

aakash
  • 1
  • 2
  • More information needed, where is `string` defined? You're using it before defining it. You're also trying to open the file for writing before you've closed it from the first time. – Matt Cummins Sep 27 '22 at 23:51
  • "Here in lines[p] if I remove \n the lines below it get removed." No, it doesn't. Instead, it gets stuck on the end of `lines[p]`, because there is no longer a `\n` getting written into the file. If you understand what `\n` means in the first place, the linked duplicate should answer your question. If not, please try to study a Python tutorial. – Karl Knechtel Sep 28 '22 at 00:13

1 Answers1

0

Taking a few guesses at what your intent here is. You want to open a file, find a line starting with a given prefix, replace it with something else, then write back to the file? There's a few mistakes here if that's the case

  1. You're trying to open a file you already have open. You should close it first.
  2. string is not defined before you use it, assuming this is the full code.
  3. When opening a file using with, you don't need to close it after.

With these in mind you want something like

with open('elk.in','r') as f:
    lines = f.readlines()

for idx, line in enumerate(lines):
    if line.startswith('vkloff'):
        p = idx
        break

lines[p] = f'{string}\n'
with open('elk.in','w') as out:
    out.writelines(lines)

But really more information is needed about what you're trying to achieve here.

Matt Cummins
  • 309
  • 5