简体   繁体   中英

Python3 find last occurrence string then write

I am trying to create a script that will add a zone to the end of named.conf if domain does not exist (last occurrence of the marker #--# and write to next line) . I appear to be caught in a paradox of list vs. file object. If I open as list, I can find my string but cannot write to the file without closing list object first which is not a good solution. If I open the file as file object, I get an object error trying to use find

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

or

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

What is the proper way to to open a file for search and editing in 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")

The file is only open for reading so that is why you get the error, whether you use in or == depends on whether the line can contain the domain name or the line needs to be equal to the domain name.

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

To find the last occurrence of a line and write a line after:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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