我正在尝试创建一个脚本,如果域不存在,则会将区域添加到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")
答案 0 :(得分:1)
该文件仅供阅读使用,这就是您收到错误的原因,无论您使用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)