Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
997 views
in Technique[技术] by (71.8m points)

python how to write to specific line in existing txt file

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 + '
'
               M.writelines(lines)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 )

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...