0

I am trying to write a program in python which will modify another python program. Steps will be as follows:

  1. 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" )
  1. 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.
  2. 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.
  3. 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" )
M.liza
  • 115
  • 10

1 Answers1

0

You have pyh_new listed twice. What you could do is call the name of the first one phy_new_read, and the second one phy_new_write. Then you would want to make phy_new_read return the line_list. return line_list. You would then be able to do:

if __name__ == '__main__':

    lines = pyh_new_read( "pyh.py" )

    #grab the specific lines that you want. See 
    # https://stackoverflow.com/questions/2081836/reading-specific-lines-only-python

    pyh_new_write( lines )

See the following question for how to get specific lines from a file Reading specific lines only (Python)

hostingutilities.com
  • 8,894
  • 3
  • 41
  • 51