繁体   English   中英

python3找到最后出现的字符串然后写

[英]Python3 find last occurrence string then write

我正在尝试创建一个脚本,如果域不存在(最后出现###标记并写入下一行),该脚本会将一个区域添加到named.conf的末尾。 我似乎陷入了列表与文件对象的悖论。 如果我以列表形式打开,则可以找到我的字符串,但是如果不先关闭列表对象就无法写入文件,这不是一个好的解决方案。 如果我将文件作为文件对象打开,则在尝试使用find时出现对象错误

Traceback (most recent call last):
  File "named.py", line 10, in <module>
    answer = mylist.find('#--#')
AttributeError: 'list' object has no attribute 'find'

要么

  File "named.py", line 12, in <module>
    f.write("   zone \""+name+"\" {\n")
io.UnsupportedOperation: not writable

在Python3中打开文件进行搜索和编辑的正确方法是什么?

import sys
import string
import os.path

name = input("Enter the domain to configure zone for? ")
#fd = open( "named.conf", 'w')
if os.path.lexists("named.conf"):
        with open('named.conf') as f:
                mylist = list(f)
                print(mylist)
                f.write("      zone \""+name+"\" {\n")

该文件仅开放供读取,因此这就是您收到错误的原因,无论您使用in还是==取决于该行可以包含域名还是该行必须等于域名。

if os.path.lexists("named.conf"):  
    with open('named.conf') as f:
        found = False
        for line in f:
            # if domain is in the line break and end
            if name in line.rstrip():
                found = True
                break
    # if found is still False we did not find the domain
    # so open the file and append the domain name
    if not found:
        with open('named.conf', "a") as f:
            f.write("      zone \{}\ {\n".format(name))

要查找最后出现的一行并在以下位置写一行:

if os.path.lexists("named.conf"):
        with open('named.conf') as f:
            position = -1
            for ind, line in enumerate(f):
                # if line is  #--#
                if "#--#" == line.rstrip():
                    # keep updating index so will point to last occurrence at the end
                    position = ind 
        if position != -1: # if we found at least one match
            with open('named.conf', "r+") as f:
                for ind, line in enumerate(f):
                    if ind == position: # find same line again
                        # write line and new line
                        f.write("{}{}\n".format(line,your_new_line))
                    else:
                        f.write(line)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM