2017-07-19 113 views
0

我写一个脚本,它读取输入文件,取值,需要写在输出模板中的特定位置(行),我是绝对的菜鸟,不能做到这一点。它要么写在输出的第一行,要么写在最后一行。python如何写入特定的行在现有的txt文件

打开文件作为 'R +'

使用file.write(XYZ)命令

Confudes有关如何解释蟒写入特定的行,例如。线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

你不能做到这一点,你可以用'seek'围绕一个文件浏览,但只对特定的行书写方式读取 - >修改 - >写 – user3012759

+0

因此不一站式-code店。请进一步调查,试着让它起作用,向我们展示(相关)代码并告诉我们您失败的位置。 –

+0

抱歉,不想冒犯任何人,阅读相当少的论坛和网站,并且变得有点沮丧因为无法解决问题(从昨天开始),我会用相关代码更新问题,感谢您的帮助。 – Matija

回答

1

可以读取该文件,然后,写入一些特定的线。

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) 
+0

非常感谢你,尽管Python重复了文件,但是正确的行被替换了 – Matija