2

Im writing a script which reads input file, takes the value and needs to write in the specific place (line) in output template, I'm absolute rookie, can't do it. It either writes in the first line of the output or in the last one.

opened file as 'r+'

used file.write(xyz) command

Confudes about how to explain to python to write to specific line, eg. line 17 (which is blank line in output template)

edit:

with open (MCNP_input, 'r+') as M:
           line_to_replace = 17
           lines = M.readlines()
           if len(lines) > int (line_to_replace):
               lines[line_to_replace] = shape_sphere + radius + '\n'
               M.writelines(lines)
Community
  • 1
  • 1
Matija
  • 23
  • 1
  • 1
  • 5
  • you can't just do that, you can use `seek` to navigate around a file, but only way to write on specific line is read -> modify -> write – user3012759 Jul 19 '17 at 10:24
  • SO is not a one-stop-code-shop. Please investigate a bit more, try to get this to work, show us (relevant) code and tell us where you failed. – rickvdbosch Jul 19 '17 at 10:33
  • sorry, didn't want to offend anyone, read quite few forums and websites, and became a bit frustrated cause could't solve the problem (since yesterday), I'll update question with relevant piece of code, thanks for the help. – Matija Jul 19 '17 at 10:56

1 Answers1

1

You can read the file and then, write into some specific line.

line_to_replace = 17 #the line we want to remplace
my_file = 'myfile.txt'

with open(my_file, 'r') as file:
    lines = file.readlines()
#now we have an array of lines. If we want to edit the line 17...

if len(lines) > int(line_to_replace):
    lines[line_to_replace] = 'The text you want here'

with open(my_file, 'w') as file:
    file.writelines( lines )
Víctor López
  • 819
  • 1
  • 7
  • 19
  • thank you so much, it helped even though Python duplicates file but with correct line replaced – Matija Jul 19 '17 at 10:52
  • 1
    @Víctor While this solution was accepted for this use case, consider the format in the file the user is accessing constantly changes depending on input and now the desired text originally located on line 17 is now on, say, line 25. Can you think of a better way to keep track of this instead of having to go back and change the line number every time? – Rook Mar 19 '19 at 21:52
  • 6
    What if this file is 1000 000 lines long? This is not efficient. – Jonathan Spiller Jul 23 '20 at 07:43