how to replace (update) text in a file line by line

前端 未结 3 841
[愿得一人]
[愿得一人] 2020-11-30 08:10

I am trying to replace text in a text file by reading each line, testing it, then writing if it needs to be updated. I DO NOT want to save as a new file, as my script alrea

3条回答
  •  迷失自我
    2020-11-30 08:44

    A (relatively) safe way to replace a line in a file.

    #!/usr/bin/python 
    # defensive programming style
    # function to replace a line in a file
    # and not destroy data in case of error
    
    def replace_line(filepath, oldline, newline ):
      """ 
      replace a line in a temporary file, 
      then copy it over into the 
      original file if everything goes well
    
      """
    
     # quick parameter checks 
      assert os.exists(filepath)          # ! 
      assert ( oldline and str(oldline) ) # is not empty and is a string
      assert ( newline and str(newline) )
    
      replaced = False
      written  = False
    
      try:
    
        with open(filepath, 'r+') as f:    # open for read/write -- alias to f       
    
          lines = f.readlines()            # get all lines in file
    
          if oldline not in lines:
              pass                         # line not found in file, do nothing
    
          else:
            tmpfile = NamedTemporaryFile(delete=True)  # temp file opened for writing
    
            for line in lines:           # process each line
              if line == oldline:        # find the line we want 
                tmpfile.write(newline)   # replace it 
                replaced = True  
              else:
                tmpfile.write(oldline)   # write old line unchanged
    
            if replaced:                   # overwrite the original file     
              f.seek(0)                    # beginning of file
              f.truncate()                 # empties out original file
    
              for tmplines in tmpfile: 
                f.write(tmplines)          # writes each line to original file
              written = True  
    
          tmpfile.close()              # tmpfile auto deleted    
          f.close()                          # we opened it , we close it 
    
      except IOError, ioe:                 # if something bad happened.
        printf ("ERROR" , ioe)
        f.close()                        
        return False
    
      return replaced and written        # replacement happened with no errors = True 
    

    (note: this replaces entire lines only , and all of the lines that match in the file)

提交回复
热议问题