bomba
bomba

Reputation: 151

python edit file with if statement

I want to check and edit some ns zone file using a python script, because they are missing the '@' symbol at the beginning of the string

            IN      MX    10 mail.example.com

I need some clarification on verifing if before the 'IN', there'are not any other strings or chars, just blank spaces.

Here's my code

with open("zone_file.zone", "r+") as file:
    for line in file:
        string = line.lstrip()
        if line.lstrip().startswith('IN     MX'):
            line = "@"+line[1:]
            file.write(line)

but it does nothing

basically the code is

for line in file:
   if str in line:
      line= "@"+line[1:]

but I need to check the presence of chars before the IN string

edit: I have:

                IN      MX

and I want

@               IN      MX

but the blanks spaces are not fixed

edit2: also the space between IN and MX is not fixed, so I can't figure out ho to solve.

this is an example of what I have

              IN      MX    20 mail2.example.com. 
              IN  MX    50 mail3              
example.com.  IN      A     192.0.2.1             
              IN      AAAA  2001:db8:10::1       
ns            IN  A     192.0.2.2             
              IN      AAAA  2001:db8:10::2      

edit 3: this is my updated code, but it doesn't work yet

with open(filename, 'r+') as f:
    file_di_zona = f.readlines()
    for line in file_di_zona:
        if line.lstrip().startswith('IN') and 'MX' in line:
            line = '@' + line[1:]
            #print line
            file_di_zona.write(str(line))

Upvotes: 1

Views: 300

Answers (1)

sundar nataraj
sundar nataraj

Reputation: 8692

for line in file:
    if line.lstrip().startswith('IN') and 'MX' in line:
       line = "@"+line[1:]
       file.write(line)

best solution since if u have large file this will read fine and change it faster than normal

import sys

for line in sys.stdin:
   if line.lstrip().startswith('IN') and 'MX' in line:
       line = '@' + line[1:]
   print line

save this as it is in a python file test.py

now go to the folder open terminal note both the test.py and ur zones file should be in same directory or give right path to read file

print the command

python test.py < zone_file.zone > modifiedzone.zone

Upvotes: 1

Related Questions