-2

let's say I have a file Example.txt like this:

alpha_1 = 10

%alpha_2 = 20

Now, I'd like to have a python script which performs these tasks:

  1. If the line containing alpha_1 parameter is not commented (% symbol), to rewrite the line adding %, like it is with alpha_2

  2. To perform the task in 1. independently of the line order

  3. To leave untouched the rest of the file Example.txt

The file I wrote is:

with open('Example.txt', 'r+') as config:
      while 1:
        line = config.readline()
        if not line:
           break

    # remove line returns
    line = line.strip('\r\n')
    # make sure it has useful data
    if (not "=" in line) or (line[0] == '%'):
      continue
    # split across equal sign
    line = line.split("=",1)
    this_param = line[0].strip()
    this_value = line[1].strip()

    for case in switch(this_param):    

       if case("alpha1"):
          string = ('% alpha1 =', this_value )
          s = str(string)
          config.write(s)

Up to now the output is the same Example.txt with a further line (%alpha1 =, 10) down the original line alpha1 = 10.

Thanks everybody

Rocco B.
  • 117
  • 1
  • 12
  • Welcome to Stack Overflow. Please take the [tour] and read about [ask]. There is no Python in your question other than asking us to write it. We're here to help you write better Python, but you need to make a start at least. Have a look at the [**`fileinput`**](https://docs.python.org/3/library/fileinput.html) module function [`input`](https://docs.python.org/3/library/fileinput.html#fileinput.input) with parameter `inplace=True` for starters. – Peter Wood Feb 20 '18 at 17:11

1 Answers1

0

I found the solution after a while. Everything can be easily done writing everything on another file and substituting it at the end.

configfile2 = open('Example.txt' + '_temp',"w")
    with open('Example.txt', 'r') as configfile:
      while 1:          
       line = configfile.readline()
       string = line
       if not line:
        break

       # remove line returns
       line = line.strip('\r\n')
       # make sure it has useful data
       if (not "=" in line) or (line[0] == '%'):  
         configfile2.write(string)
       else: 
         # split across equal sign
         line = line.split("=",1)
         this_param = line[0].strip()
         this_value = line[1].strip()

         #float values
         if this_param == "alpha1":
           stringalt = '% alpha1 = '+ this_value + '   \r\n'
           configfile2.write(stringalt)                            
         else:
           configfile2.write(string) 

    configfile.close()    
    configfile2.close()
    # the file is now replaced
    os.remove('Example.txt' )
    os.rename('Example.txt' + '_temp','Example.txt' )
Rocco B.
  • 117
  • 1
  • 12