2017-07-19 519 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