I am trying to write a program in python which will modify another python program. Steps will be as follows:
- I have a program (pyh.py)which contains below-mentioned lines and output is as follows
output:
Number of lines: 6 
Number of characters: 65
code for pyh.py:
import os
import sys
def pyh( filename ):
    if ( os.path.isfile( filename ) ):
        file = open( filename, 'r' )
        line_list = file.readlines()
        pyh_compute_size( line_list )
        file.close()
    else:
        print( "File " + filename + " does not exist." )
def pyh_compute_size( line_list ):
    line_count = 0; char_count = 0
    for line in line_list:
        line_count += 1
        char_count += len( line )
    print( "Number of lines: " + str( line_count ) )
    print( "Number of characters: " + str( char_count ) )
if __name__ == '__main__':
    pyh( "text_a.txt" )
- What I am trying to do is, I am writing another python program called ‘modifier.py’ which will open ‘pyh.py’ (in the same directory) and read the file then close it.
- Then open the same file ‘pyh.py’ for writing. It will go through the list of line and write line 1 to 20 in the new file (modifier.py). After that, it removes the newline from the end of it, and add;print ("Additional Part") to the end, and then add a newline.
- After that, it will write from 21 to end to the new file (modifier.py).
When I run the ‘modifier.py’ it will modify the ‘pyh.py’ (for line between 20 & 21). When ‘pyh.py’ is modified then it should show the below output.
Additional Part
Additional Part
Number of lines: 6 
Number of characters: 65
I am trying to do the step 3 & 4 but unable to find the appropriate way. I am new in python. So it would be really great if someone helps me to solve it.
code for modifier.py is as follow:
import os
import sys
def pyh_new( filename ):
    if ( os.path.isfile( filename ) ):
        file = open( filename, 'r' )
        line_list = file.readlines()
        file.close()
def pyh_new( filename ):
    if ( os.path.isfile( filename ) ):
        file = open( filename, 'w' )
        line_list = file.writelines()
        #need to write 
        file.close()
if __name__ == '__main__':
    pyh_new( "pyh.py" )
 
    