python用if语句编辑文件 [英] python edit file with if statement

查看:50
本文介绍了python用if语句编辑文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 python 脚本检查和编辑一些 ns 区域文件,因为它们缺少字符串开头的@"符号

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

我需要澄清一下,是否在IN"之前没有任何其他字符串或字符,只有空格.

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

这是我的代码

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)

但它什么都不做

基本上是代码

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

但我需要检查 IN 字符串之前是否存在字符

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

我有:

                IN      MX

我想要

@               IN      MX

但空格不固定

edit2:IN和MX之间的空格也不是固定的,所以我不知道怎么解决.

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      

编辑 3:这是我更新后的代码,但它还不能工作

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))

推荐答案

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

将其保存在 python 文件 test.py 中

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

现在转到文件夹打开终端注意 test.py 和 ur 区域文件应该在同一目录中或提供读取文件的正确路径

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

打印命令

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

这篇关于python用if语句编辑文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆