python如何在现有的txt-fi中写入特定的行

2024-03-29 14:42:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我写的脚本读输入文件,取值,需要写在输出模板的特定位置(行),我是绝对菜鸟,不能这样做。它要么写入输出的第一行,要么写入最后一行。在

opened file as 'r+'

used file.write(xyz) command

混淆了如何向python解释如何写入特定行,例如第17行(输出模板中的空行)

编辑:

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)

Tags: 文件to脚本模板aslinecommandreplace
1条回答
网友
1楼 · 发布于 2024-03-29 14:42:20

你可以先读取文件,然后写入某一行。在

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 )

相关问题 更多 >