python file inserts and replaces specific line instances in detail

  • 2020-06-12 09:31:37
  • OfStack

python file inserts and replaces specific line instances in detail

python offers read,write, but like many languages it doesn't seem to offer insert. Of course, it would be possible if it were provided, but the introduction of insert would cause a number of other problems, such as the fact that crash could be dropped during the insertion process and the rest of the content could not be written back.

However, fileinput makes it easy to implement the requirement of inserting in a particular row:

Python code


import os 
import fileinput 
def file_insert(fname,linenos=[],strings=[]): 
  """ 
  Insert several strings to lines with linenos repectively. 
 
  The elements in linenos must be in increasing order and len(strings) 
  must be equal to or less than len(linenos). 
 
  The extra lines ( if len(linenos)> len(strings)) will be inserted 
  with blank line. 
  """ 
  if os.path.exists(fname): 
    lineno = 0 
    i = 0 
    for line in fileinput.input(fname,inplace=1): 
      # inplace must be set to 1 
      # it will redirect stdout to the input file 
      lineno += 1 
      line = line.strip() 
      if i<len(linenos) and linenos[i]==lineno: 
        if i>=len(strings): 
          print "\n",line 
        else: 
          print strings[i] 
          print line 
        i += 1 
      else: 
        print line 
file_insert('a.txt',[1,4,5],['insert1','insert4']) 

Note that fileinput. input's inplace must be set to 1 in order for stdout to be redirected to the input file.

Of course, fileinput. input can be used not only to insert in a row, but also to insert or replace in a particular pattern of rows (such as those ending in salary:), implementing a small sed.

The above is a simple example of python file specific line insert and replace, if you do not understand or good Suggestions please go to the comments or community questions and exchanges, using thank you reading, I hope to help you, thank you for your support to this site!


Related articles: