如何将字符串添加到特定行

问题描述:

我有一个包含50行的文件。我怎么能添加一个字符串“-----”到一个特定的行说第20行使用Python/Linux?如何将字符串添加到特定行

+0

拆分回车(\ n)并遍历所有增加var的行。每20行,插入你需要的任何字符串。你也可以有一个20回车的正则表达式 – 2013-03-06 03:32:58

您是否尝试过这样的事情?:

exp = 20 # the line where text need to be added or exp that calculates it for ex %2 

with open(filename, 'r') as f: 
    lines = f.readlines() 

with open(filename, 'w') as f: 
    for i,line in enumerate(lines): 
     if i == exp: 
      f.write('------') 
     f.write(line) 

如果您需要编辑的行数差异可以更新这样上面的代码:

def update_file(filename, ln): 
    with open(filename, 'r') as f: 
     lines = f.readlines() 

    with open(filename, 'w') as f: 
     for idx,line in enumerate(lines): 
      (idx in ln and f.write('------')) 
      f.write(line) 
+0

什么是'exp'?我假设你的意思是20. – squiguy 2013-03-06 03:27:55

+0

@squiguy是)我的意思是需要添加文本的行 – 2013-03-06 03:28:43

+0

'exp'是一些与OP想要的匹配的表达式。 – askewchan 2013-03-06 03:28:58

$ head -n 20 input.txt > output.txt 
$ echo "---" >> output.txt 
$ tail -n 30 input.txt >> output.txt 

如果文件读取很大,并且您不想一次读取内存中的整个文件:

from tempfile import mkstemp 
from shutil import move 
from os import remove, close 

line_number = 20 

file_path = "myfile.txt" 

fh_r = open(file_path) 
fh, abs_path = mkstemp() 
fh_w = open(abs_path, 'w') 

for i, line in enumerate(fh_r): 
    if i == line_number - 1: 
     fh_w.write('-----' + line) 
    else: 
     fh_w.write(line) 

fh_r.close() 
close(fh) 
fh_w.close() 

remove(file_path) 
move(abs_path, file_path) 

注:我用Alok的回答here作为参考。