python如何写入现有txt文件中的特定行

发布于 2021-01-29 15:02:53

我正在编写一个脚本,该脚本读取输入文件,获取值并需要在输出模板的特定位置(行)写入,我绝对是菜鸟,无法做到。它要么写在输出的第一行,要么写在最后一行。

打开的文件为“ r +”

使用的file.write(xyz)命令

关于如何向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)
关注者
0
被浏览
136
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    您可以读取文件,然后写入某些特定行。

    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 )
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看