change some lines from a read file

norseman norseman at
Mon May 4 16:54:26 EDT 2009

Anthra Norell wrote:
> utab wrote:
>> Dear all,
>> I have to change some lines from a template file, which is rather long
>> to paste here, but I would like to make some parts of some lines
>> optional with my command line arguments but I could not see this
>> directly, I can count the line numbers and decide on this basis to
>> decide the lines to be configured to my will.
>> More specifically, say, I have a that file includes
>> this is an example python file to play around
>> .
>> .
>> .
>> some lines
>> .
>> .
>> .
>> . -> an option line for example.
>> .
>> .
>> .
>> -> another option line so on.
>> and execute the script
>> ./myScript option1 option2
>> so that the options at correct locations will be written.
>> Any other options for this simple job that i can improve my Python a
>> bit as well.
>> Best,
>> Umut
>> -- 
> Your description is not explicit enough to convey your intention. If 
> your template file is too long to post, post a short representative 
> section, an input data sample and a hand-edited sample of the output 
> data you want to generate. You will get more and better advice. .
> Frederic
> -- 


Assuming the total number of changes is not large,

put OPTION1 where you want it to go in the text
put OPTION2  (same)

import sys

if len(sys.argv) >1:
   OPTION1 = sys.argv[1]
   OPTION1 = "some default stuff"

similar for OPTION2
if len(sys.argv) >2:
   like above
and any others

print section1+OPTION1+section2+OPTION2....

           just using the line count  (in place of "print sect..")
line_number= 0
for i in template:
   if line_number matches line number to place Opt1
     print OPTION1
   elif line_number matches v2
     print OPTION2
and so forth
     print i   (line from template NOT being changed)
   line_number += Line_number

you can group line number and replacement on command line
runprogram (43,"use this instead") (56,....
and parse inside program before opening template

one thing to watch out for:
    for i in file...  often returns just one character at a time, 
meaning you will have to track EOL's yourself  OR
import the readline and use it to stand a better chance of getting what 
you expect from a read file function.

Today: 20090504
Logic outline, No particular version


More information about the Python-list mailing list