简体   繁体   中英

how to insert an specific line before another line, into a text file with python and without inserting any empty lines between any lines?

I want to extract the element stiffness matrix from Abaqus input file. the contents of the last lines of the file are as follows:

** 
** OUTPUT REQUESTS
** 
*Restart, write, frequency=0
** 
** FIELD OUTPUT: F-Output-1
** 
*Output, field, variable=PRESELECT
*End Step

in order to extract the element stiffness matrix from an input file, we should the following line into the input file, ie the line before the ((*End Step)) line:

*ELEMENT MATRIX OUTPUT,ELSET=m,STIFFNESS=YES,MASS=NO,OUTPUTFILE=USER

I want to add this line into my input file through python language which is the scripting language of Abaqus software. I try the following code to another text file to test this code, but after executing these lines, between each of two lines, it inserts an empty line which I don't want these empty line:(in the following code, I just want to show that, other codes create empty lines)

import fileinput

processing_foo1s = False

for line in fileinput.input('Input8.inp', inplace=1):
  if line.startswith('*Output,'):
    processing_foo1s = True
  else:
    if processing_foo1s:
      print ('foo bar')
    processing_foo1s = False
  print (line,)

This code will do exactly what you need:

with open('Input8.inp', 'r+') as f:
    _text = ''
    for line in f:
        if line.startswith('*End Step'):
            _text += '*ELEMENT MATRIX OUTPUT,ELSET=m,STIFFNESS=YES,MASS=NO,OUTPUTFILE=USER\n'

        _text += line

    f.seek(0)
    f.write(_text)
    f.truncate()

Explanation:

  1. Open file in read-write mode.
  2. Create temp variable
  3. Iterate file line by line
  4. If found line which starts with '*End Step' - add your custom line to temp variable
  5. Add iterated line to temp variable
  6. Go to start of file
  7. Write temp variable to it
  8. Delete the remaining lines in file ( which should not be present, but in case they somehow where not iterated - delete them )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM