Ameet Kumar
Ameet Kumar

Reputation: 1

Editing text file through command line argument in Python

I want to edit text file by passing integer number via command line argument in Python. However my code is not working, can some one point me where I am wrong.

    import sys, argparse
    def main(argv=None):
    if argv is None:
        argv=sys.argv[1:]
        p = argparse.ArgumentParser(description="Editing omnetpp.ini")
        p.add_argument('arg1', action='store', default= 1, type=int, help="number of clients")
        args = p.parse_args(argv)
        n = args.arg1
        f = open('C:\\Users\Abcd\Desktop\Omnet\omnetpp.ini', 'a')
        for i in range(n):
            f.write('*.voipClient['+str(i)+'].udpApp['+str(i)+'].destAddresses = "voipGateway"\n')
            f.write('*.voipGateway.udpApp['+str(i)+'].destAddresses   = "voipClient['+str(i)+']"\n')
        f.close()

If integer number 5 is passed via command line argument then it should add following lines in text file, which is not happening Output

*.voipClient[0].udpApp[0].destAddresses = "voipGateway"
*.voipGateway.udpApp[0].destAddresses   = "voipClient[0]"
*.voipClient[1].udpApp[1].destAddresses = "voipGateway"
*.voipGateway.udpApp[1].destAddresses   = "voipClient[1]"
*.voipClient[2].udpApp[2].destAddresses = "voipGateway"
*.voipGateway.udpApp[2].destAddresses   = "voipClient[2]"
*.voipClient[3].udpApp[3].destAddresses = "voipGateway"
*.voipGateway.udpApp[3].destAddresses   = "voipClient[3]"
*.voipClient[4].udpApp[4].destAddresses = "voipGateway"
*.voipGateway.udpApp[4].destAddresses   = "voipClient[4]"

I am following these steps:

  1. Code is saved in test.py
  2. From command line C:\Users\Abcd\Desktop>python test.py 5

Upvotes: 0

Views: 617

Answers (1)

catchmeifyoutry
catchmeifyoutry

Reputation: 7359

Don't close the file in the loop, as soon as it is closed you cannot write to it anymore (in fact, an error should be thrown if you try to write to a closed file object). Instead, close it after the loop. Also, to put each sentence on a new line, end the string with the newline symbol \n (sort of pressing "ENTER").

f = open('C:\\Users\Abcd\Desktop\Omnet\omnetpp.ini', 'a')
for i in range(n):
    f.write('*.voipClient['+str(i)+'].udpApp['+str(i)+'].destAddresses = "voipGateway"\n')
    f.write('*.voipGateway.udpApp['+str(i)+'].destAddresses   = "voipClient['+str(i)+']"\n')
f.close()

EDIT

By the way, as Rostyslav Dzinko said in the comments, the way you defined your code is not how you define a main function. In fact, try something like this (see also this SO question):

if __name__ == '__main__':
    p = argparse.ArgumentParser(description="Editing omnetpp.ini")
    p.add_argument('arg1', action='store', default= 1, type=int, help="number of clients")
    args = p.parse_args()

Upvotes: 1

Related Questions